tags:

views:

61

answers:

3

Hi guys. I 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...

+6  A: 
str_replace(str_split($stringA),'',$stringB);
Wrikken
+3  A: 

Hey,

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.

clausvdb
Good idea but bad execution, you should use preg_replace() instead, as ereg has been deprecated in 5.3. I'll append it to your answer if you don't mind.
Josh Davis
I would highly suggest against ereg_replace. It is depreciated in PHP 5.3. That and for something this simple, str_replace will do just fine, no need for a regular expression.
Brad F Jacobs
I would definitely recommend that approach over `str_replace()` as it is more flexible and its performance is in the same order of magnitude.
Josh Davis
Oops, preg_replace is the better choice, of course. The str_replace() approach seems wiser anyway, since you don't have to worry about escaped characters either.
clausvdb
+2  A: 

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)
Josh Davis
Good point about single-byte encoding.
George Marian