简体   繁体   中英

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?

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

一种解决方案可能是:

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM