0

I have a problem when replacing strings with preg_replace.

function addClass($search, $string) {

    return preg_replace("/\b($search)\b/", "<div class=mark>$1</div>", $string);

}

$string = "We won again"; 
$result  = addClass("We", $string);

output ---> <div class=mark>We</div> won again

I want to make $search for multiple strings.

$string = "We won again"; 
$result  = addClass(array("We", "again"), $string);

output ---> <div class=mark>We</div> won <div class=mark>again</div>

How can I create multiple searches, to put strings in an array?

Thanks in advance.

2 Answers 2

3

You can use or expresion in regex - (We|again)

function addClass($search, $string) {
    return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}

And, if you want to save the old syntax, make an array from a single string:

function addClass($search, $string) {
    if(! is_array($search)) $search = array($search);
    return preg_replace("/\b(". implode('|', $search) . ")\b/", "<div class=mark>$1</div>", $string);
}

demo

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

2 Comments

ahh, my bad. i type "we" instead "We", how to make it case insensitive?
Glad to help. Good luck!
2

The alternative solution using is_array and array_map functions:

function addClass($search, $string) {
    $search = (is_array($search))? array_map(function($v) { return "/\b($v)\b/"; }, $search) : ["/\b($search)\b/"];
    return preg_replace($search, "<div class=mark>$1</div>", $string);
}

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.