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

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?