开发者

Reg exp to replace the whole word if any word contains any non alphanumeric character or space

e.g

string = "This is a re@lly long long,long! sentence";

becomes

string = "This is a long sentence";

Basically so all non-alphanumeric wor开发者_开发知识库ds or removed keeping spaces in tacked

Any ideas?


Try this one:

preg_replace("/(^|\\s)\\S*?[^ a-zA-Z0-9]\\S*?(\\s|$)/", '$1', $string)


I think something like this is quite intuitive:

<?php

$text = "This is a #@^!%$ re@lly long long,long! sentence";
print preg_replace("/\\w*[^\\w\\s]\\w*\\s*/", "", $text);

?>

The output is (as seen on ideone.com):

This is a long sentence

This works by matching any sequence of \w* that is followed by [^\w\s] (neither a word character nor a whitespace), followed by any sequence of \w*\s*. Anything matching this can be deleted, so it's replaced with "".

See also

  • regular-expressions.info/Character class, Repetition
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜