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

主宰稳场 提交于 2019-12-23 04:05:42

问题


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!


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/8256907/regex-in-php-as-an-example-replace-b-tags-with-i

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!