asDca21
asDca21

Reputation: 161

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?

Upvotes: 0

Views: 1308

Answers (2)

Jan
Jan

Reputation: 43199

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.

Upvotes: 2

Thomas Ayoub
Thomas Ayoub

Reputation: 29481

You can replace like so:

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

Upvotes: 0

Related Questions