简体   繁体   English

正则表达式(php)-匹配非字母数字字符的块

[英]Regular Expressions (php)- match blocks of non alphanumerical charactors

I'm in need to modify a given string to contain only alpha numerical characters, dots (.) and commas. 我需要修改给定的字符串以仅包含字母数字字符,点(。)和逗号。 If the string contains any character other than az, AZ , 0-9 or a dot(.), they should be replaced with a comma sign, I'm using this: 如果字符串包含az,AZ,0-9或点(。)以外的其他任何字符,则应将它们替换为逗号,我正在使用以下字符:

$string = "dycloro 987 stackOVERflow !|,!!friday";
$newstring = preg_replace('/[^a-zA-Z0-9\.]/', ',', $string);

This returns, 返回,

dycloro,987,stackOVERflow,,,,,,friday dycloro,987,StackOverflow上周五,,,,,,

But I'm in need to get the following instead. 但是我需要获取以下内容。

dycloro,987,stackOVERflow,friday dycloro,987,计算器,周五

(Note the " !|,!!" part in $string is replaced with a single comma sign). (请注意,$ string中的“!|,!!”部分将替换为单个逗号)。 Ideally, I want to replace a block of disallowed characters with a single comma sign. 理想情况下,我想用单个逗号符号代替一个禁止的字符块。 I figured out that $newstring = preg_replace('/,{2,}/', ',', $newstring); 我发现$newstring = preg_replace('/,{2,}/', ',', $newstring); replaces multiple comma signs with a single comma. 用单个逗号替换多个逗号符号。 But is there any way to do this in a faster, or better way ? 但是,有什么方法可以更快或更更好地做到这一点? How do I do this in a single regular expression match ? 如何在单个正则表达式匹配中做到这一点? and is there any process time or memory difference in them ? 并且它们之间有任何处理时间或内存差异吗? This is regular expressions will be run against few megabytes of user input so I'm curious about it as well. 这是正则表达式,将针对几兆字节的用户输入运行,因此我对此也很好奇。

Thank you! 谢谢!

Just add a plus sign + , meaning "one or more of what I just mentioned", after the character class: 在字符类之后,只需添加一个加号+ ,表示“我刚才提到的一个或多个”:

$string = "dycloro 987 stackOVERflow !|,!!friday";
$newstring = preg_replace('/[^a-zA-Z0-9\.]+/', ',', $string);

See http://www.php.net/manual/en/regexp.reference.repetition.php . 参见http://www.php.net/manual/en/regexp.reference.repetition.php

试试这个

$newstring = preg_replace('/[^a-zA-Z0-9\.]+/', ',', $string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM