Jonathan
Jonathan

Reputation: 724

str_replace() only to find exact match

I want to replace the exact match using str_replace().

My code:

$html = array("<br>", "<b>", "</b>", "<i>", "</i>");
$custom = array("--", "*", "**", "\\", "\\\\");

$arr = str_ireplace($custom, $html, $arr);

But if the original string is hello *this** should be bold then it replaces each * sign with <b>:

hello <b>this<b><b> should be bold

Instead of how I want it to look:

hello <b>this</b> should be bold

How can I solve this?

Upvotes: 1

Views: 331

Answers (1)

Nick
Nick

Reputation: 147216

This is a good application for strtr as it will replace in order of longest substring first:

$html = array("<br>", "<b>", "</b>", "<i>", "</i>");
$custom = array("--", "*", "**", "\\", "\\\\");
$arr = 'hello *this** should be bold';
echo strtr($arr, array_combine($custom, $html));

Output:

hello <b>this</b> should be bold

Demo on 3v4l.org

Upvotes: 3

Related Questions