2

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...

3 Answers 3

6
str_replace(str_split($stringA),'',$stringB);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

4 Comments

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.
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.
I would definitely recommend that approach over str_replace() as it is more flexible and its performance is in the same order of magnitude.
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.
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.