Peter Peter - 3 months ago 12
PHP Question

Change string value

I'm trying to replace

^
to
<span>
. But, I failed. I tried with
str_replace
but don't work properly.

So, my original value is:

^ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon&#039;t lose this.


You can see, that have a color value, starts with
^
and I want to replace that for:
'<span style=color"#ffcb4a">
.

But with my
str_replace
, I got this:

<span style='color:#'ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon&#039;t lose this.


As u can see, it doesn't work.

$item_description = str_replace('^', "<span style='color:#'" . '', $item_description);

Answer

You'll need to use a regex for this.

$item_description = '^ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon\'t lose this.';
echo preg_replace('/\^(.*?)\h/', 
'<span style="color:#$1">', 
$item_description);

Output:

<span style="color:#ffcb4a">Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon't lose this.

It also is unclear where you want the span to end..

This regex captures everything between a ^ and the first horizontal white space.

Regex101 Demo: https://regex101.com/r/bA4dC8/1

You can't use the str_replace because you don't know where to close the span.

If you wanted to pull the first 6 characters after ^ you could change

(.*?)\h

to

(.{6})

Which says any 6 characters.

Example:

$item_description = '^ffcb4a Special reward of the territory war. \rUsed to manufacture Rank IX gears. \rDon\'t lose this.';
    echo preg_replace('/\^(.{6})/', 
    '<span style="color:#$1">', 
    $item_description);