yoyoma
yoyoma

Reputation: 3536

Regex match text in single quotes with specific second quote

I have this php version

 $string = "'Fred's Company' is... ";
 // OR
 $string = "'Fred's Company' has... ";
 $match = "/'((?:[^']+|\b'\b)+)'/";
 preg_match_all($match, $string, $t);

So the regex above works if the string doesn't itself contain single quote so 'Fred Company', it will find Fred Company, however with the version above it will only find Fred.

To fix, I need the 2nd single quote to match the ' is or ' has version of the string, therefore getting back the full Fred's Company is/has, and still work for Fred Company is/has.

How can I change the above regex for this ?

Upvotes: 0

Views: 43

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520878

You may use a smart negative lookahead which asserts that the closing single quote does not occur inside two other outer single quotes:

$string = "'Fred's Company' has members in 'ATL'";
$match = "/'.*?'(?!\S)/";
preg_match_all($match, $string, $t);
print_r($t[0][0]);

This prints:

Array
(
    [0] => 'Fred's Company'
    [1] => 'ATL'
)

The regex pattern asserts that the single quote does not occur embedded within a word. Admittedly, this fails for the edge case of possessive (genitive) s, e.g.

Fred's employees' paychecks are going up this year.

Upvotes: 2

Related Questions