phpreplacepreg-replaceapostrophe

Replace words in a string including plural variations with apostrophes


I want to link matches for specific words in a sentence. Overall this is easy, and sample code could go like this:

$words = array("Facebook", "Apple");
$text = "Is Facebook's vr hardware better than Apple's current prototype?";
foreach($words as $w) {
    $pattern = '/' . $w .'\b/i';
    $link = '<a href="/blah/' . strtolower($w) . '">' . $w . '</a>';
    $text = preg_replace($pattern, $link, $text);
}
print $text;

However I would like to catch variations of words that have 's (apostrophe-s).

To do that I need to search for the two possible variations (with and without the 's), but the outcome also affects what text used in the replacement.

I'm drawing a blank on how to pro-actively used preg_match and then alter preg_replace based on the outcome. Any advice appreciated.


Solution

  • try using the optional ? quantifier and parenthesis.

    $pattern = '/' . $w .'(\'s)?\b/i';

    should match either version.

    now, to use the match in your replacement, you can add an extra set of parenthesis, like this:

    $pattern = '/(' . $w .'(\'s)?)\b/i';

    then insert the matched string into your replacement, like this:

    $link = '<a href="/blah/' . strtolower($w) . '">$1</a>';

    the $1 in the replacement string will be replaced with whatever the outer parenthesis of the match contains.