得到< tag>之间的所有内容和</tag>用PHP [英] get everything between <tag> and </tag> with php
本文介绍了得到< tag>之间的所有内容和</tag>用PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用正则表达式在字符串中捕获字符串.
I'm trying to grab a string within a string using regex.
我已经看了看,但是我似乎无法获得我必须工作的任何示例.
I've looked and looked but I can't seem to get any of the examples I have to work.
我需要获取html标签< code>和</code>及其之间的所有内容.
I need to grab the html tags <code> and </code> and everything in between them.
然后我需要从父字符串中提取匹配的字符串,对二者进行操作,
Then I need to pull the matched string from the parent string, do operations on both,
然后将匹配的字符串放回父字符串中.
then put the matched string back into the parent string.
这是我的代码:
$content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. <code>Donec sed erat vel diam ultricies commodo. Nunc venenatis tellus eu quam suscipit quis fermentum dolor vehicula.</code>"
$regex='';
$code = preg_match($regex, $text, $matches);
我已经尝试过这些方法,但没有成功:
I've already tried these without success:
$regex = "/<code\s*(.*)\>(.*)<\/code>/";
$regex = "/<code>(.*)<\/code>/";
推荐答案
您可以使用以下内容:
$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
-
\b
确保不会捕获错字(如<codeS>
). - 第一个模式
[^>]*
捕获具有属性(例如,类)的标签的内容. - 最后,标志
s
用换行符捕获内容. \b
ensures that a typo (like<codeS>
) is not captured.- The first pattern
[^>]*
captures the content of a tag with attributes (eg a class). - Finally, the flag
s
capture content with newlines.
在此处查看结果: http://lumadis.be/regex/test_regex.php ?id = 1081
这篇关于得到< tag>之间的所有内容和</tag>用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文