user2818254
user2818254

Reputation: 87

How to remove before and after string in php

Here is my string so far

Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day - Feb 14th|#|Occasions=>Thinking of you

I want below output

Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day|#|Occasions=>Thinking of you

As per above output i want to remove - Feb 14th from the string.

Note:- - Feb 14th this string would be dynamic like some time it would be - DEC 25TH OR - 27th Nov etc .. Any help is highly appreciated. Thanks.

Upvotes: 0

Views: 70

Answers (2)

baao
baao

Reputation: 73251

After your update, this will work:

$str = 'Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day - Feb 14th|#|Occasions=>Thinking of you'
$a = strpos($str,'-');
$b = strpos($str, '|', $a);
if ($b) {
    $c = $b - $a;
    echo substr_replace($str, '', $a - 1, $c + 1);
}
else {
    echo strstr($str,' -', true);
}

Output:

Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day|#|Occasions=>Thinking of you

Upvotes: 3

Rizier123
Rizier123

Reputation: 59701

This should work for you:

$str = "Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day - Feb 14th|#|Occasions=>Thinking of you";
echo $str . "<br />";
$str = preg_replace('/\s-(.*?)\|/', '|', $str);
echo $str . "<br />";

Output:

Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day - Feb 14th|#|Occasions=>Thinking of you
Birthdays=>Birthday||Birthday for Girlfriend|#|Valentines Day=>Valentine Combos||Valentine Roses||Valentines Day|#|Occasions=>Thinking of you

Upvotes: 3

Related Questions