0

I have a string:

$test = "Test string<i> hello world</i>."

Then I am running

$test = preg_replace('/(<i>{1}\s*)([\w*\d*\D*\W*\x*\O*\S*\s*]*?)(<\/i>{1})/', '<italic>$2</italic>', $test);

And the result is

Test string<italic>hello world</italic>.

Why is the whitespace before the hello world lost?

Here is an example http://pastebin.com/SXFhsCGK.

Thank you.

5
  • 2
    [\w*\d*\D*\W*\x*\O*\S*\s*] Ouch. What are you trying to do here? Commented Apr 3, 2014 at 8:39
  • I am trying to match everything between <i> and </i>. The goal is to replace <i> tags by <italic> tags Commented Apr 3, 2014 at 8:40
  • Sure, this can be done, but the question is not how to do it differently, but why this happens. Commented Apr 3, 2014 at 8:44
  • 1
    This consumes Your whitespace after <i>: (<i>{1}\s*). BTW I guess <i>{1} isn't what You intend, it says "match the <, then match the i and then match (exactly one, which is default) >". Commented Apr 3, 2014 at 8:45
  • 2
    preg_replace('%<(/?)i>%', '<$1italic>', $test) Commented Apr 3, 2014 at 8:47

1 Answer 1

2

Solution

As @Reeno puts it in the comments, replacing the <i> tags by <italic> ones directly is the way to go (assuming they're all tags you want to replace):

preg_replace('%<(/?)i>%', '<$1italic>', $test)

What was wrong with your regex

The space is lost because it is matched by the \s* in <i>{1}\s*, so it's not in the capturing group.

Also, writing [\w\W...] means "match any character that is either alphanumeric OR any character that is not alphanumeric"... So basically, match everything.

And the {1} quantifier is (always?) useless (>{1} is equivalent to >).

Heuristically, what you wanted to do was use this regex (s is so that the dot matches newline too):

~<i>(.*?)</i>~s
Sign up to request clarification or add additional context in comments.

Comments

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.