doushen8391 2015-04-10 00:45
浏览 81
已采纳

查找并替换它周围的字符串和字符

StackOverflow.

Let's say I have this variable:

$paragraph = "This is a bunch of random information. Here is a URL: http://example.com/inventory/personid Thanks for checking it out!";

I need to detect if the $paragraph has a URL in it, even if the personid changes, and then save it as a variable, then replace it with some new code. For example, this is what I should walk away with:

$url = "http://example.com/inventory/personid";
$replace = "newinformation!";
$newparagraph = "This is a bunch of random information. Here is a URL: newinformation! Thanks for checking it out!";

I'm pretty sure this has to do with strpos(), but I have no idea past that.

Edit: personid would be represented as something along the lines of #730_2_1697061248 but the numbers would change.

  • 写回答

1条回答 默认 最新

  • dongting3135 2015-04-10 00:51
    关注

    Just use preg_replace(), like this to replace the url:

    echo $newparagraph = preg_replace("/\b" . preg_quote($url, "/") . "\S*/", $replace, $paragraph);
    

    output:

    This is a bunch of random information. Here is a URL: newinformation! Thanks for checking it out!
    

    regex explanation:

    /\b . preg_quote($url, "/") . \S*
    
    • \b assert position at a word boundary (^\w|\w$|\W\w|\w\W) test matches the characters test literally (case sensitive)
    • preg_quote($url, "/") -> http\:\/\/example\.com\/inventory\/
    • \S* match any non-white space character [^ \t\f ]
      • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真