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 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端