【问题标题】:php replace substring with regexphp用正则表达式替换子字符串
【发布时间】:2012-03-13 14:13:08
【问题描述】:

好的,我知道有数以万亿计的类似问题,但我发现很难做到这一点。 我有一些这种格式的字符串:

$x = '<iframe src="[File:19]"></iframe>';
$y = '<img src=[File:2212] />';
$z = '<source src="[File:42]" />';

我正在尝试获取在 File: 之后给出的 ID,并将整个 [File:xxx] 替换为另一个字符串。我正在尝试如下,但似乎我无法完全理解 preg_replace 的用法。

$file = ('<iframe src="[File:134]"></frame>');
$rex = "/^.*(\[File:[0-9]{1,}\])/i" ;
if ( preg_match($rex, $file, $match) ) {
    echo 'OK';
}
$file = preg_replace ($rex, "http://lala.com/la.pdf", $file);
echo "<br>".htmlentities($file)."<br>";

您能否给我一些提示,告诉我如何做到这一点?

提前致谢。

【问题讨论】:

  • 您可以使用preg_match_all 并删除^.*..(应该可以)但是实际上您应该为此使用PHP DOM

标签: php regex html-parsing


【解决方案1】:

这应该可以解决问题:

preg_match('/\[File:(\d+)\]/i', $str, $match)

$match[0] 将包含整个字符串,$match[1] 将仅包含数字。
正则表达式匹配后,您可以使用str_replace 从字符串中删除 $match[0]。

例子:

$x = '<iframe src="[File:19]"></iframe>';
preg_match('/\[File:(\d+)\]/i', $x, $match);
var_dump($match);

给予:

array(2) {
  [0]=>
  string(9) "[File:19]"
  [1]=>
  string(2) "19"
}

【讨论】:

    【解决方案2】:

    改变这两行

    $rex = "/^.*(\[File:[0-9]{1,}\])/i" ;
    
    $file = preg_replace ($rex, "http://lala.com/la.pdf", $file);
    

    到:

    $rex = "/^(.*)\[File:[0-9]{1,}\]/i" ;
    
    $file = preg_replace ($rex, "$1http://lala.com/la.pdf", $file);
    

    这会将[File...] 之前的内容捕获到第1 组中,然后在替换部分中,将此组(即$1)添加到替换字符串的前面。

    可以改写为:

    $rex = "/\[File:\d+\]/i" ;
    
    $file = preg_replace ($rex, "http://lala.com/la.pdf", $file);
    

    【讨论】:

    • 是我一个人,还是/^(.*)\[File不仅很没用,而且对性能也很不利? /^.*\[File/ 归结为 /\[File,不是吗?如果你不在正则表达式中捕获它,你不必替换它,对吧?
    • @BerryLangerak:是的,你是对的,我刚刚采用了 OP 的正则表达式,只做了最少的改动。
    【解决方案3】:

    这应该可行:

    <?php
    $formats[] = '<iframe src="[File:19]"></iframe>';
    $formats[] = '<img src=[File:2212] />';
    $formats[] = '<source src="[File:42]" />';
    
    
    foreach( $formats as $format ) {
    
        $regex = '~\[File:(\d+)\]~';
    
        $replace = function( $matches ) {
            return 'http://lala.com/la.pdf?id=' . $matches[1];
        };
    
        var_dump( preg_replace_callback( $regex, $replace, $format ) );
    }
    

    我为替换创建了一个 lambda,因为我感觉您想在 File: 之后使用 id 而不是仅仅丢弃它。玩得开心。如果您有任何问题,请告诉。

    【讨论】:

    • 您不需要在括号中捕获整个表达式。默认情况下,整个匹配区域存储在 $matches[0] 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2018-07-13
    相关资源
    最近更新 更多