Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: remove string character found in another string

Tags:

string

php

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

like image 609
FlyingCat Avatar asked May 01 '26 15:05

FlyingCat


2 Answers

str_replace(str_split($stringA),'',$stringB);
like image 68
Wrikken Avatar answered May 04 '26 04:05

Wrikken


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.

like image 25
clausvdb Avatar answered May 04 '26 03:05

clausvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!