I building a function that will check a string and add paragraph and bold tags if the word at the begining of the string matches any word in list of words.
I’ve based it roughly on a bad word filter I found on Stackoverflow and its working great except for words that contain parentheses and I can’t work out how to escape them!
So in the below example "Item one", "Item two", "Item three" all match.
But "item (four)" fails.
How can I escape the parentheses in the word array so the regex still works?
//array of words to match
$words= array("Item one", "Item two", "Item three", "item (four)");
//strings that should match
$string = "item (four)" //fails
$string = "item one" //works
//loop through array of word and if a match is found add p and b tags
for ($i = 0; $i < count($words); $i++) {
if (preg_match('/^' . $words[$i] . '(:|b)/i', $string ) === 1) {
$stringInput = preg_replace("/^" . $words[$i] . "(:|b)/i", "<p><b>" . ucwords(strtolower($words[$i])) . " </b></p>", $string );
}
}
`
I’ve tried to escape the parentheses in the array and I’ve tried split the word in the array to add the delimiter that way
2
Answers
You can use
See the demo online.
NOTES:
$stringInput = $string;
must be used since the$string
value is going to be modified in a loop(?!Bw)
s are adaptive word boundaries that only require a word boundary if the adjoining character on the right/left is a word charpreg_quote($words[$i], "/")
escapes the chars inside the$words
.To escape regex strings you need to use
preg_quote()
function.