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; } 
    }
1

2 Answers 2

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_-]%

Sign up to request clarification or add additional context in comments.

3 Comments

Oops. Copied and edited the wrong line. See my edit.
Thank you very much, it was very simple after all!
Glad to help! Please remember to select an answer! :)
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.