开发者

Regex-PHP: How can be find if the string equal to <br> with regex and not with ==

开发者 https://www.devze.com 2023-02-07 14:41 出处:网络
How can i replacea 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)

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>
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消