PHP正则表达式:字符串以及以...结尾

时间:2012-11-28 19:25:40

标签: php regex expression

$ptn = "/^Response.+?[:] /";
$str = "Response from Moore Auto: Thanks for your feedback";
$rpltxt = "";
echo preg_replace($ptn, $rpltxt, $str);

“Moore Auto”是一个变量名,所以我只需要冒号和空格后面的文字。在这种情况下,期望的最终结果将是字符串“感谢您的反馈”。非常感谢!

3 个答案:

答案 0 :(得分:3)

简单地使用substr(),就像这样:

$str = 'Response from Moore Auto: Thanks for your feedback';
echo substr($str, strpos($str,':')+2);  //echoes "Thanks for your feedback"

答案 1 :(得分:0)

如果有多个冒号,Damiens解决方案不起作用。如果第一部分不包含冒号,这应该始终有效:

<?php 
$ptn = "/^Response[^:]+:\s*(.*)$/";
$str = "Response from Moore Auto: Thanks for your feedback";
if (preg_match($ptn, $str, $match)) {
    $text = $match[1];
    echo $text; //Thanks for your feedback
}
?>

答案 2 :(得分:0)

尝试

<?php 
$ptn = "/^(Response.+[:])(.*?)/";
$str = "Response from Moore Auto: Thanks for your feedback";
$rpltxt = "$2";
echo preg_replace($ptn, $rpltxt, $str);
?>