简体   繁体   English

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

[英]PHP Regular Expression: String starts with and ends with

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

"Moore Auto" is a variable name, so I simply need the text after the colon and space. “Moore Auto”是一个变量名,所以我只需要冒号和空格后面的文字。 Desired final result would be the string "Thanks for your feedback" in this case. 在这种情况下,期望的最终结果将是字符串“感谢您的反馈”。 Much appreciated! 非常感激!

Simple with substr() , like this: 使用substr()简单,如下所示:

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

Damiens solution does not work, if there is more than one colon. 如果有多个冒号,Damiens解决方案不起作用。 This should always work if the first part doesn't contain a colon: 如果第一部分不包含冒号,这应该始终有效:

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

try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM