dthl8036 2018-06-29 07:33
浏览 46
已采纳

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;
?>
  • 写回答

1条回答 默认 最新

  • dongtiao5094 2018-06-29 07:53
    关注

    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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题