繁体   English   中英

简单的PHP preg_replace

[英]Simple php preg_replace

这是我的第一个问题。 我需要做我想是简单的php preg_replace()替换的事情,但是我对正则表达式一无所知。

我有一个html格式的文本字符串,由多个" + figure("br") + " (包括开始和结束引号)分隔。 我需要将它们更改为<em class="br"></em> ,其中“ br”是我必须保留的参数。

我要替换200多个文字。 当然,我可以分别替换前置和后置,但是想要以正确的方式进行。 在此先感谢您,并原谅我的英语。

输入样例: <p>Bien!</p> <p>Gana <b>Material</b> por el <b>Doble Ataque</b> al " + figure("bn") + "c6 ya la " + figure("br") + "h8.</p>

示例输出: <p>Bien!</p><p>Gana <b>Material</b> por el <b>Doble Ataque</b> al <em class="bn"></em>c6 ya la <em class="br"></em>h8.</p>

[编辑为包含真实数据]

我认为我们需要有关您的方案的更多信息,以便为您提供有用的信息。 做您描述的最简单的方法是做类似的事情:

$output = preg_replace('/.*\("br"\).*/', '<span class="br"></span>', $input);

但是我不知道那是否是您真正想要的。 这将去除初始字符串中的所有文本,并用<span class="br"></span>块替换,所以剩下的就是字符串<span class="br"></span>

在我看来,您想要的是将看起来像foo("bar")baz块更改为类似foo<span class="bar"></span>baz 如果是这样,您可能会想要这样的东西:

$output = preg_replace('/\("(.*?)"\).*/', '<span class="$1"></span>', $input);

但是,这只是我阅读问题的最佳方式。 为了真正解决该问题,我们需要更多地了解pre_stringpost_stringbr分别代表什么,以及它们可能如何变化。 一些示例输入和输出文本可能会有所帮助,有关您将其用于什么的信息也可能会有所帮助。

编辑:我认为您的最新编辑使它更加清晰。 看起来您正在尝试使用正则表达式解析JavaScript或其他编程语言,由于regex限制 ,您通常无法完美地做到这一点。 但是,以下情况在大多数情况下应该有效:

$pattern = '/(["\'])\s*\+\s*\w+\((["\'])(.*?)\2\)\s*\+\s*\1/'
$output = preg_replace($pattern, '<span class="$3"></span>', $input);

说明:

/
(["\'])    #Either " or '. This is captured in backreference 1 so that it can be matched later.
  \s*\+\s* #A literal + symbol surrounded by any amount of whitespace. 
  \w+      #At least one word character (alphanumeric or _). This is "figure" in your example.
  \(       #A literal ( character.
   (["\']) #Either " or '. This is captured in backreference 2.
     (.*?) #Any number of characters, but the `?` makes it lazy so it won't match all the way to the last `") + "` in the document.
   \2      #Backreference 2. This matches the " or ' from earlier. I didn't use ["\'] again because I didn't want something like 'blah" to match.
  \)       #A literal ) character.
  \s*\+\s* #A literal + symbol surrounded by any amount of whitespace.
\1         #Backreference 1, to match the first " or ' quote in the string.
/

希望这相对容易理解。 很难解释正则表达式模式在做什么,因此,如果仍然难以理解,我感到抱歉。 如果您仍然感到困惑,这是一些有关反向引用惰性量词的信息。

我不确定反向引用的语法。 这些天我通常不使用PHP编写代码。 如果有人想纠正我,我会欢迎。

如果您有一个可变的前后字符串(或者您的情况下带有元字符的字符串),那么我认为最好在此处使用一些正则表达式转义:

//  " + figure("br") + "
$pre = '" + figure';
$post = ' + "';

// escape
$pre = preg_quote($pre, "#");
$post = preg_quote($post, "#");

// then the regex becomes easy
$string = preg_replace(
               "#$pre\(\"(\w+)\"\)$post#",
               '<em class="$1"></em>',
               $string
);

我假设您正在转换一些源代码?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM