0

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?

1
  • Your regex looks close (and good), but I would use this: /\[SYS \d+\](.*?)\[\/SYS\]/ ... find on this, and replace with the first capture group. Commented Aug 25, 2016 at 14:59

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You can replace like so:

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

5 Comments

It will remove "[SYS n]" and "[/SYS]" only? what if I want to replace the text between these tags later?
@asDca21 then use $re = "/\\[SYS \\d+\\](.*?)\\[\\/SYS\\]/";
@ThomasAyoub: You have far more backslashes then needed here :) Also, consider using another delimiter, e.g. ~.
@Jan which backslash would you remove?
See answer above :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.