简体   繁体   English

如何在PHP中使用正则表达式查找和替换两个标签之间的字符串?

[英]How to find and replace string between two tags using regex in PHP?

If we have a text like this: 如果我们有这样的文字:

[SYS 1]Page 1 from 2:[/SYS] [SYS 1]第2页的第1页:[/ SYS]

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum只是印刷和排版行业的伪文本。 Lorem Ipsum has been the industry's standard ... Lorem Ipsum一直是行业标准...

[SYS 2]Page 2 from 2:[/SYS] [SYS 2]第2页,第2页:[/ SYS]

It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 它不仅生存了五个世纪,而且在电子排版方面也取得了飞跃,但基本上没有改变。

How should I keep only text between [SYS] and [/SYS] tags? 如何在[SYS]和[/ SYS]标记之间仅保留文本? like this: 像这样:

Page 1 from 2: 第1页,共2页:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum只是印刷和排版行业的伪文本。 Lorem Ipsum has been the industry's standard ... Lorem Ipsum一直是行业标准...

Page 2 from 2: 第2页,共2页:

It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. 它不仅生存了五个世纪,而且在电子排版方面也取得了飞跃,但基本上没有改变。

I think the following regex would find the text inside two tags without attributes: 我认为以下正则表达式会在两个没有属性的标记中找到文本:

/\[SYS\](.+?)\[\/SYS\]/

But how should I replace the entire element with the inner text (or any other string) for that tag? 但是,我应该如何用该标签的内部文本(或任何其他字符串)替换整个元素?

Use the following expression: 使用以下表达式:

\[SYS[^]]*\](.+?)\[/SYS\]

And replace with $1 , see a demo on regex101.com . 并替换为$1 ,请参阅regex101.com上的演示


In PHP : PHP

 $regex = '~\\[SYS[^]]*\\](.+?)\\[/SYS\\]~'; $string = preg_replace($regex, '$1', $your_original_string); 

See a demo for the complete code on ideone.com . 有关ideone.com的完整代码,请参见演示。

You can replace like so: 您可以这样替换:

$re = "/\\[\\/?SYS(?:\\s\\d+)?\\]/";
$str = "[SYS 1]Page 1 from 2:[/SYS]";
echo preg_replace($re, "", $str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM