user1861037
user1861037

Reputation: 13

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!

Upvotes: 1

Views: 1390

Answers (3)

Andy Ecca
Andy Ecca

Reputation: 1969

try

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

Upvotes: 0

Tom
Tom

Reputation: 5068

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

Upvotes: 0

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"

Upvotes: 3

Related Questions