I want to replace word groups by links.
The word groups are defined in a multi-dimensional array. There will be thousands of terms to be replaced, so an unindexed, light-weight and multi-dimensional array is needed.
Nothing should be replaced when the term is followed by brackets or inside square brackets.
Problem: The regex itself works fine, but the replacement breaks when the word groups include regex syntax characters like + ? / ( etc. So I need to mask them. I tried all variations I can think of but it won't work for all cases. I can't mask them in $text or $s.
<?php
$text = "<html><body><pre>
Replace all foo / bar / baz cases here:
Case 1: Text Foo text.
Case 2: Text 'Foo' Bar text Foo.
Case 3: Text Foobar (2) text.
Case 4: Text Bar & Baz.
Case 5: Text Bar Baz?
Case 6: Text Bar? & Baz?
Case 7: Text Bar-X.
Replace nothing here (text followed by brackets) or [inside square brackets]:
Case 1: Text Foo (text).
Case 2: Text 'Foo' Bar (text) Foo (text).
Case 3: Text Foobar (2) (text).
Case 4: Text Bar & Baz (text).
Case 5: Text Bar Baz (text).
Case 6: Text Bar? & Baz (text).
Case 7: Text Bar-X (text).
Case 8: [Text Foo]
</pre></body></html>";
$s = array(
array("t" => "Foo", "u" => "http://www.foo.net"),
array("t" => "'Foo' Bar", "u" => "http://www.foo.net"),
array("t" => "Foobar (2)", "u" => "http://www.foo.net"),
array("t" => "Bar & Baz", "u" => "http://www.foo.net"),
array("t" => "Bar Baz?", "u" => "http://www.foo.net"),
array("t" => "Bar? & Baz?", "u" => "http://www.foo.net"),
array("t" => "Bar-X", "u" => "http://www.foo.net")
);
$replaced = $text;
foreach ($s as $i => $row) {
# $replaced = preg_replace('/(?='.preg_quote($row["t"]).'[^\]][^(]+$)\b'.preg_quote($row["t"]).'\b/mS',
# $replaced = preg_replace('/(?='.preg_quote($row["t"], '/').'[^\]][^(]+$)\b'.preg_quote($row["t"], '/').'\b/mS',
# $replaced = preg_replace('/(?=\Q'.$row["t"].'\E[^\]][^(]+$)\b\Q'.$row["t"].'\E\b/mS',
$replaced = preg_replace('/(?='.$row["t"].'[^\]][^(])\b'.$row["t"].'\b/mS',
'<a href="'.$row["u"].'">'.$row["t"].'</a>',
$replaced);
}
echo $replaced;
?>