How can i replace a string with '' if string equel to <br>
only with regex
I don't know regex, and I cant do this with regular expression (I know other ways, please don't write them)
Case 1 - replace because开发者_StackOverflow input equal to <br>
:
input== '<br>' => result=''
Case 2 - not replace if input not equal to <br>
:
input==' xcx<br>dfd<br>' => result:' xcx<br>dfd<br>'
Thanks
You can do:
$result = preg_replace('/^<br>$/', '', $input);
Explanation:
^ : Start anchor
<br> : A literal <br>
$ : End anchor
The regex is just the string you want to match placed in between the start and end anchor. The anchors are important, without them you'll end up replacing <br>
in string that has <br>
as its substring.
$string = preg_replace('~^<br>$~', '', $string);
^
denotes the start of a string, $
the end. But what's the point? Doing a comparison is much more appropriate:
if ('<br>' === $string) {
$string = '';
}
<?php
$input = '<br>';
if ($input == '<br>') {
$result = '';
}
echo $result; // Output: (nothing)
$input = ' xcx<br>dfd<br>';
if ($input == '<br>') {
$result = '';
}
echo $result; // Output: xcx<br>dfd<br>
?>
精彩评论