开发者

PHP: remove string character found in another string

开发者 https://www.devze.com 2023-01-08 18:48 出处:网络
I开发者_C百科 am trying to compare two strings and remove any characters that appear in second string.

I开发者_C百科 am trying to compare two strings and remove any characters that appear in second string. For example:

$stringA="abcdefg" ;
$stringB="ayfcghifh" ;

I want $stringB to be "yhih". Are there any ways to do it? Thanks for the help...


str_replace(str_split($stringA),'',$stringB);


echo ereg_replace("[" . $stringA . "]", "", $stringB);

would be a convenient way to do so.


Or using preg_replace()

$stringB = preg_replace('/[' . preg_quote($stringA, '/') . ']/', '', $stringB);

As an added benefit, you can have case-insensitivity with the /i modifier and Unicode support with /u.


You can use multiple needles in str_replace() to remove each character from $stringA. Assuming we're talking about single-byte encoding, you can use str_split() to separate each character, which gives you:

$stringB = str_replace(str_split($stringA, 1), '', $stringB)
0

精彩评论

暂无评论...
验证码 换一张
取 消