获取 <tag> 之间的所有内容和</tag>用 php [英] get everything between <tag> and </tag> with php

查看:20
本文介绍了获取 <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. &lt;code>Donec sed erat vel diam ultricies commodo. Nunc venenatis tellus eu quam suscipit quis fermentum dolor vehicula.&lt;/code>"
$regex='';
$code = preg_match($regex, $text, $matches);

我已经尝试过这些但没有成功:

I've already tried these without success:

$regex = "/<codes*(.*)>(.*)</code>/";
$regex = "/<code>(.*)</code>/";

推荐答案

您可以使用以下内容:

$regex = '#<s*?code[^>]*>(.*?)</code[^>]*>#s';

  •  确保不会捕获错字(如 ).
  • 第一个模式 [^>]* 捕获带有属性(例如类)的标签的内容.
  • 最后,标志 s 用换行符捕获内容.
    •  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

      这篇关于获取 &lt;tag&gt; 之间的所有内容和&lt;/tag&gt;用 php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆