1

I have a list of names and I'm using preg_replace to make a certain part of those names bold. I was using str_replace but I needed a limit on it.

However I'm getting the error "Delimiter must not be alphanumeric or backslash". After some research I found out that it's happening because I'm missing slashes on my pattern variable.

However I've been trying and I can't get it right and I'm not finding any example like mine. Thank you for your help.

while($row = $result->fetch_array()) {
        $name = $row['name'];

    $array = explode(' ',trim($name));
    $array_length = count($array);

    for ($i=0; $i<$array_length; $i++ ) {
        $letters = substr($array[$i], 0, $q_length);
        if ($letters = $q) {
        $bold_name = '<strong>'.$letters.'</strong>';
        $final_name = preg_replace($letters, $bold_name, $array[$i], 1);
        $array[$i] = $final_name; } 
    }
Penny
  • 253
  • 1
  • 5
  • 15
  • possible duplicate of [Delimiter must not be alphanumeric or backslash and preg\_match](http://stackoverflow.com/questions/7660545/delimiter-must-not-be-alphanumeric-or-backslash-and-preg-match) – HamZa Jan 02 '15 at 11:22

2 Answers2

2

You need a delimiter on your regex. For example, using ~:

$final_name = preg_replace('~'.$letters.'~', $bold_name, $array[$i], 1);

You can read more at the documentation for PCRE delimiters and the documentation for preg_replace.

From the docs:

When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/

#^[^0-9]$#

+php+

%[a-zA-Z0-9_-]%

Community
  • 1
  • 1
elixenide
  • 44,308
  • 16
  • 74
  • 100
0

you just need to add simple delimiter to first parameter of preg_replace.

Add forward slashes to your $letters (However other delimiters can be used also.)

$final_name = preg_replace('/'.$letters.'/', $bold_name, $array[$i], 1);

As you mentioned in question, answer is in itself that Delimiter must not be alphanumeric or backslash.

shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50