preg_replace - 留下不需要的字符
我有一个字符串:
$string = "Hello World!";
我想将其转换为 URL 友好标记,并且我开发了一个函数来执行此操作:
function stripJunk($string){
$string = str_replace(" ", "-", $string);
$string = preg_replace("/[^a-zA-Z]\s/", "", $string);
$string = strtolower($string);
return $string;
}
但是,当我在上面运行我的 $string
时,我得到以下内容:
$string = "hello-world!";
似乎有一些字符从我的 preg_replace 中溜走,即使根据我的理解,它们不应该如此。
它应该是这样的:
$string = "hello-world";
这是怎么回事? (这应该很简单!)
编辑 1:我不知道正则表达式是初学者的东西,但无论如何。 此外,删除字符串中的 \s 不会产生所需的结果。
期望的结果是:
- 所有空格都转换为破折号。
- 所有剩余的非 AZ 或 0-9 字符都将被删除。
- 然后将该字符串转换为小写。
编辑 2+:稍微清理了我的代码。
I've got a string:
$string = "Hello World!";
I want to turn it into a URL friendly tag, and I've developed a function to do it:
function stripJunk($string){
$string = str_replace(" ", "-", $string);
$string = preg_replace("/[^a-zA-Z]\s/", "", $string);
$string = strtolower($string);
return $string;
}
However, when I run my $string
through it above, I get the following:
$string = "hello-world!";
It seems that there are characters slipping through my preg_replace, even though from what I understand, they shouldn't be.
It should read like this:
$string = "hello-world";
What's going on here? (This should be easy peasy lemon squeasy!)
Edit 1: I wasn't aware that regular expressions were beginners stuff, but whatever. Additionally, removing the \s in my string does not produce the desired result.
The desired result is:
- All spaces are converted to dashes.
- All remaining characters that are not A-Z or 0-9 are removed.
- The string is then converted to lower case.
Edit 2+: Cleaned up my code just a little.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下对我来说效果很好:
The following works just fine to me:
模式末尾的 \s 意味着您将仅替换紧随其后的空白字符的非字母字符。 您可能希望将 \s 放在方括号内,以便也保留空格,并且稍后可以用破折号替换。
如果您还想允许使用数字,则需要在方括号内添加 0-9。
例如:
The \s at the end of your pattern means that you will only replace non-alphabetical characters which are immediately followed by a whitespace character. You probably want the \s within the square brackets so that whitespace is also preserved and can later be replaced with a dash.
You will need to add 0-9 inside the square brackets if you want to also allow numbers.
For example:
您可以连续使用一些正则表达式来删除垃圾:
这应该可以解决问题,快乐的 PHP'ing!
You could use some regular expressions in a row to remove the junk:
This should do the trick, happy PHP'ing!
那这个呢?
如果这不起作用:
那有效吗?
What about this?
if that does not work:
Does that work?