Javawag
Javawag

Reputation: 1567

RegEx in PHP - as an example, replace <B> tags with <I>

I know next to nothing about RegEx, even after reading a few tutorials :\ I basically just want to know how to replace tags with tags - so how do you match the tag and how do you state that you want to replace it, keeping the tag text as it is? I saw something about a $1 in the replacement string but I don't know what that refers to?

Be as in-depth as you can, I'm brand new to this and need help!

Upvotes: 1

Views: 1472

Answers (2)

ioseb
ioseb

Reputation: 16951

Here is the very simple example:

    $regex = '~
      <b>           #match opening <b> tag
      (.*?)         #match anything in between
      </b>          #match closing </b> tag
    ~six';

    preg_replace($regex, '<i>$1</i>', $input);

In this example regular expression matches opening B tag content within tag and closing B tag. Following pattern (.*?) groups content separately so you can later refer to it like $1.

If we modify expression slightly by adding more grouping parenthesis:

    $regex = '~
      (<b>)         #match opening <b> tag
      (.*?)         #match anything in between
      (</b>)        #match closing </b> tag
    ~six';

    preg_replace($regex, '<i>$2</i>', $input);

Replacement part will change from $1 to $2, as far as we have three groups we are referring to (.*?) with $2 as it's a second group etc...

http://www.php.net/manual/en/reference.pcre.pattern.syntax.php

Upvotes: 2

tamasgal
tamasgal

Reputation: 26269

I would suggest you to look at some tutorial Videos, since reading them obviously didn't help, I could imagine that answering how to replace <B> with <I> wouldn't help neither.

Here is video tutorial on youtube for example: Regular Expression Tutorials Part # 1 for PHP - Javascript

Upvotes: -1

Related Questions