PHP; 如何在分隔符和字符串结尾之间获取字符串?

I have a string like this:

$string = "This is my name: David";

And I want to turn it into this:

This is my name: <a href="https://www.example.com?q=David">David</a>

Means:

Get everything between "name: " (first delimiter) and the end of the string (second delimiter).

Set </a> after the extracted string (in this case "David").

Set <a href="https://www.example.com?q="> in front of the extracted string (in this case "David").

Insert the extracted string (in this case "David") after "q=" like: q=David

I'm good in PHP but I always stuck with regular expressions.

Is the anybody who can help me to do this?

EDIT:

This is what I have so far:

<?php
$string = "This is my name: David";
if(stripos($string, "name: ") !== false) {
$string = str_replace("name: ", "<a href=\"https://www.example.com?q=\">", $string);
$string = implode(array($string, "</a>"));
}
echo $string;
?>

You may use this preg_replace:

$string = preg_replace('/\b(name:\h*)(.+)/i', 
  '$1<a href="https://www.example.com?q=$2">$2</a>', $string);

RegEx Details:

  • \b: Start with a word boundary
  • (name:\h*): Match name: followed by 0 ore more horizontal whitespaces characters in capture group #1
  • (.+): Match 1+ of any characters in capture group #2
  • /i: Ignore case modifier
  • In substitution we use $1 and $2 to get our formatted html