Reputation: 263
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; }
}
Upvotes: 1
Views: 3035
Reputation: 5752
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
.
Upvotes: 0
Reputation: 44833
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_-]%
Upvotes: 2