简体   繁体   中英

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]

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

[SYS 2]Page 2 from 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? like this:

Page 1 from 2:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard ...

Page 2 from 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 .


In PHP :

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

See a demo for the complete code on ideone.com .

You can replace like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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