Mikey Barker
Mikey Barker

Reputation: 83

Replacing an exact string in PHP

I have a string that looks like:

$String = "Size,Please Select,L Kids,XL Kids,S,M,L,XL"

I would like to replace ',XL' with ',XL (Out of Stock)' however i do not want it to replace 'XL Kids' too.

So i would need an outcome like:

$String_replaced ="Size,Please Select,L Kids,XL Kids,S,M,L,XL (Out Of Stock)"

I have tried using String replace but this will not work, i understand i will have to use preg replace but i am unsure how to do that.

Can anyone help?

Upvotes: 2

Views: 1918

Answers (4)

Toto
Toto

Reputation: 91385

I'd use a negative lookahead:

$String = "Size,Please Select,L Kids,XL Kids,S,M,L,XL";
$String_replaced  = preg_replace('/\bXL\b(?! Kids)/', 'XL (Out of Stock)', $String);
echo $String_replaced ,"\n";

output:

Size,Please Select,L Kids,XL Kids,S,M,L,XL (Out of Stock)

Upvotes: 0

user1524571
user1524571

Reputation: 63

Although preg_replace is perfectly acceptable, a quicker alternative if this is just a 'one-off' thing is to still use string replace:

$string = "Size,Please Select,L Kids,XL Kids,S,M,L,XL";
$newString = str_replace("L,XL","L,XL (Out Of Stock)",$string);
echo $newString;

This finds all ",XL" values that are preceded immediately by L.

Upvotes: 0

anubhava
anubhava

Reputation: 785068

This lookaround based regex should work:

$repl = preg_replace('/(?<=^|,)\bXL\b(?=,|$)/', 'XL (Out of Stock)', $String);

This matches XL surrounded by word boundaries.

(?<=^|,) - Make sure XL is preceded by comma or at the start of line
(?=,|$) - Make sure XL is followed by comma or at the end of line

Upvotes: 1

schoash
schoash

Reputation: 166

One solution might be:

preg_replace("/,XL(\,|$)/", ",XL (Out of Stock),", $String);

Upvotes: 0

Related Questions