How to use regex to delete everything except some words? [duplicate]

我的梦境 提交于 2020-01-16 04:07:31

问题


Possible Duplicate:
Regular expression: match all words except

I need your help for using Regex in PHP to negate a selection. So I have a string like this : "Hello my name is tom"

What I need to do is to delete everything from this string witch is not "tom" or "jack" or "alex" so I tried :

$MyString = "Hello my name is tom"
print_r(preg_replace('#^tom|^jack|^alex#i', '', $MyString));

But it's not working...

Can you help me with that ? Thanks


回答1:


If you want to delete everything except something, may be it's better done the other way around: capture the something only? For example...

$testString = 'Hello my name is tom or jack';
$matches = array();
preg_match_all('/\b(tom|jack|alex)\b/i', $testString, $matches);
$result = implode('', $matches[0]);
echo $result; // tomjack

What you've tried to do is use a character class syntax ([^s] will match any character but s). But this doesn't work with series of characters, there's no such thing as 'word class'. )




回答2:


If you want to remove everything that is not "tom" or "jack" or "alex" you can use the following:

$MyString = "Hello my name is jack";
print_r(preg_replace('#.*(tom|jack|alex)#i', '$1', $MyString));

This replaces the whole string with just the matched name.




回答3:


regex:

\b(?!tom|jack|alex)[^\s]+\b



回答4:


You could match what you want and then reconstruct the string:

$s = 'hello my name is tom, jack and alex';

if (preg_match_all('/(?:tom|jack|alex)/', $s, $matches)) {
print_r($matches);
        $s = join('', $matches[0]);
} else {
        $s = '';
}

echo $s;

Output:

tomjackalex


来源:https://stackoverflow.com/questions/11049252/how-to-use-regex-to-delete-everything-except-some-words

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!