Jack Jack - 1 month ago 20
PHP Question

Unable to match regex

I have got the following phrase:

Mark: 5 Mike 2015-01-20


and I need to get Mike from it. I have tried to use negative lookups like this:

/^(\s+)((?!Mark\:(\d)).)*&(\w+)$/is


but it did not produce the desired result. Also there are some spaces in the begginning and the end of the phrase. Any ideas how to fix that would be welcome. Thank you.

Answer

Assuming that Mark:<optional spaces><digits><optional spaces> is a prefix for the search string (our "Mike"), and the search string is a sequence of non-space characters, then the following should do:

preg_match('/Mark\:\s*\d+\s*(\S+)/', $the_string, $m);
// $m[1] = 'Mike'

If the search string is supposed to be something more complex, then just replace \S+ with the desired pattern. You haven't specified this case, so I can't help more.

Comments