skip to Main Content

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


  1. You can use

    <?php
    
    $words= array("Item one", "Item two", "Item three", "item (four)");
    
    $string = "item (four)";  //fails    
    //$string = "item one";   //works
    
    //loop through array of word and if a match is found add p and b tags
    $stringInput = $string;
    for ($i = 0; $i < count($words); $i++) {         
        $stringInput = preg_replace("/(?!Bw)" . preg_quote($words[$i], "/") . "(?!Bw)/i", "<p><b>" . ucwords(strtolower($words[$i])) . " </b></p>", $stringInput );
    }
    echo $stringInput . PHP_EOL;
    

    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 char
    • preg_quote($words[$i], "/") escapes the chars inside the $words.
    Login or Signup to reply.
  2. To escape regex strings you need to use preg_quote() function.

    <?php
    $words = ["Item one", "Item two", "Item three", "item (four)"];
    
    $string = "item (four)";
    // $string = "item one";
    
    foreach ($words as $word) {
      $replacement = '<p><b>' . ucwords(strtolower($word)) . '</b></p>';
      $pattern = '/^' . preg_quote($word, '/') . '(:|b)/i';
      $stringInput = preg_replace($pattern, $replacement, $string);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search