str_ireplace() - 我可以获取要替换的字符串吗? [重复]

This question already has an answer here:

I have the following strings.

$string = "Welcome to Lorien.";
$search = "welcome";

Now I want to search for $search in $string and ignoring the case, so:

$result = str_ireplace($search,  '<b>'.$search.'</b>' ,$string);

$result should look like this: welcome to Lorien.

Is there a way i can use the case of $string so it looks like this: Welcome to Lorien.

Like getting the part of the string which is getting replaced and use it?

</div>

You can use preg_replace() for this:

$string = "Welcome to Lorien.";
$search = "welcome";

$result = preg_replace("/{$search}/i", '<b>$0</b>', $string);
  • The /i-flag makes the matching case-insensitive.
  • The $0 will be replaced with the matched string from the original string so the casing will always be correct.

Demo: https://3v4l.org/vN9Km

Op wants to find the string with a given pattern, as case insensitive, and uppercase and bold if I got correctly.

If that's the case, here's what needs to be done.

<?php

$string = "Welcome to Lorien.";
$search = "welcome";

echo str_ireplace($search, '<b>'.ucwords($search).'</b>', $string);
// Outputs: <b>Welcome</b> to Lorien.

Example: https://3v4l.org/Gmsqp