从字符串的末尾开始,我需要删除特定的字符串。我可以用一个循环来完成这个任务,但是我认为应该可以用正则表达式来实现。
示例:从输入字符串的末尾移除所有的注释和空格。
“你好,世界再好”
应该变成
“你好世界”。
我试过不同的排列
$input = preg_replace('/(<br>| | )*$/', '', $input);但最终我的判断力让我失望了。我该怎么做?
发布于 2013-11-12 16:29:53
你试过的正则表达式运行得很好。将Content-Type标头设置为plain可能有助于调试:
$string = "Hello world<br> <br> ";
$input = preg_replace('/(<br>| | )*$/', '', $string);
header('Content-Type: text/plain');
var_dump($input);产出:
string(11) "Hello world"3v4l演示。
发布于 2013-11-12 16:11:44
不要使用regexes解析HTML。对于DOM它是:
$doc = DOMDocument::loadHTML('Hello world<br> <br> ');
$selector = new DOMXPath($doc);
echo trim($selector->query('//text()')
->item(0)
->nodeValue
);输出:
Hello World但是,如果需要regex解决方案--尽管更了解它--请使用以下内容:
preg_match('~(.*?)( |<br>)~', $str, $matches);
echo $matches[1];发布于 2013-11-12 16:10:13
如果只是HTML/PHP标记,那么您可以使用php strip_tags函数更多信息
$userInput ="Hello world<br> <br> ";
$input = rtrim(strip_tags($userInput));//to rtrim to remove any whitespace at the endhttps://stackoverflow.com/questions/19934001
复制相似问题