Home > OS >  Is there a way to compare two strings where one is the parent string and the other a child string an
Is there a way to compare two strings where one is the parent string and the other a child string an

Time:06-14

I have two strings that look like this:

$string1 = "aaaa, bbbb, cccc, dddd, eeee, ffff, gggg";
$string2 = "aaaa, ffff";

I have extracted these strings by employing the function array_intersect in PHP and then imploding the resultant arrays into these two strings.

I would like to have elements in $string2 that appear in $string1 echoed out in bold without removing any element in $string1. For example i would like to have the following result echoed out in HTML:

aaaa, bbbb, cccc, dddd, eeee, ffff, gggg

I have implemented the following solution:

$array1 = explode(',', $string2):
foreach($array1 as $t){
   $string1= str_replace($t,'<b>'. $t.'</b>',$string1);
}
echo "$string1";

My solution works but i would like to know if there is a better/efficient/cleaner way of achieving this using PHP?

CodePudding user response:

explode-ing the strings back into arrays, so the longer string can be iterated and checking the short string, with in_array, for any matching items:

$string1 = "aaaa, bbbb, cccc, dddd, eeee, ffff, gggg";
$string2 = "aaaa, ffff";

$array1 = explode(", ", $string1);
$array2 = explode(", ", $string2);
$array3 = [];
foreach ( $array1 as $val ) {
    if ( in_array($val, $array2) ) {
        array_push($array3, "<strong>$val</strong>");
    }
    else {
        array_push($array3, $val);
    }
}
$string3 = implode(", ", $array3);

Try it here: https://onlinephp.io/c/431ec

  • Related