So - I have strings like this (string1 examples):
'aaaaabbbbbcccccword'
'aaaaabbbbbcccccwor*d'
'aaaaabbbbbcccccw**ord*'
'aaaaabbbbbccccc*word*'
And I need to remove some substring (string2) from the end of those strings along with any * characters in string2 a well as * preceding string2 and following string2. string2 is some variable. I can't think of a regex that can be used here.
//wrong example, * that might happen to be inside of $string1 are not removed :(
$string1 = 'aaaaabbbbbcccccw**ord*';
$string2 = 'word';
$result = preg_replace('#\*?' . $string2 . '\*?$#', '', $string1);
Can someone suggest a PCRE regex for that?
P.S. Can I get upvoted to like at list 15 points? SO I can upvote people?
$regexp = '#\**' . implode('\**', str_split($string2)) . '\**$#';
$result = preg_replace($regexp, '', $string1);
str_split
splits the string up into characters, and then implode
inserts \**
between each of them. Then we put \**
before and after it to grab any surrounding *
characters as well.
Here is one way of doing that:
$string1 = 'aaaaabbbbbcccccw**ord*';
$string2 = 'word';
$result = preg_replace('#\*?' . implode('\**', str_split($string2)) . '\*?$#', '',
$string1);
echo $result;
//=> aaaaabbbbbccccc