简体   繁体   中英

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. Desired final result would be the string "Thanks for your feedback" in this case. Much appreciated!

Simple with substr() , like this:

$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. 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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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