dongque8332 2012-10-07 04:04
浏览 62
已采纳

PHP preg_match或_replace从字符串中查找子字符串,同时保留匹配项

So I have this comment-esk like system I am working on, and apparently I didn't think it all the way through, however I am blocked into my method at this point for the time being and foreseeable future. That said.

I am currently using

$pattern = '/\[@(\w+):(.*)\]/';
$subject = '[@keyword:string]';
preg_match($pattern, $subject, $matches);

To find specific info from a particular pattern type. Which is something to the extent of [@keyword:string], and this works great. However in my searches to come up with this method of doing that it failed to dawn on me that the strings I am using this on also contain other stuff, such as a comment. So the over all string would look like '[@keyword:string]
Hello World`

The above bit of code will dump an array for me, first item the actual match I was looking for, the next being the keyword and the next the string. Which is great, as I use this for something else. However. Like I said I never compensated for the <br>Hello World part so. What I need to do is something very similar to the above. But only leave the <br>Hello World part as a reusable string as I am intent on rejoining the 2 strings. After my process is done. Except, the process after its done in this case is replacing the pattern I am looking for with a matching User Name, or an Image based on the keyword, which then dispatches a function to find the right name, or create the image tag for the image. Which thats fine I got that part, its just the stripping of the pattern from the string so when I get the name(s) or image back I can rejoin it to the string.

Well hopefully that makes sense.

  • 写回答

1条回答 默认 最新

  • dougou5844 2012-10-07 04:16
    关注

    Use the one of the following patterns:

    '/\[@(\w+):(.*?)\]/'
    
    '/\[@(\w+):(.*)\]/U'
    

    Note: PCRE_UNGREEDY

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口