开发者

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

开发者 https://www.devze.com 2023-01-01 08:37 出处:网络
e.g string = \"This is a re@lly long long,long! sentence\"; becomes string = \"This is a long sentence\";

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

精彩评论

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