Search code examples
phpregexpreg-replacepreg-match

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?


Solution

  • 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.