【问题标题】:Replace and extract matches with regex用正则表达式替换和提取匹配项
【发布时间】:2013-03-02 16:04:11
【问题描述】:

如何使用 preg_match_all() 获取所有匹配项并将结果替换为空字符串?

我试过这样的东西:

<?php
$comments   = array();              

$selectors  = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
function ($match) {
    $comments[] = $match[0];
    return '';
}, $input);
?>

但这并不能很好地工作,因为 $comment 变量似乎无法从匿名函数中访问。 我想我可以制作全局变量,但我真的不想那样搞乱命名空间

【问题讨论】:

  • 为什么不直接使用 preg_replace ?
  • 因为那时我无法获取/提取所有匹配项(已被替换)。或者这可能吗?
  • 在函数声明中尝试usephp.net/manual/en/functions.anonymous.php

标签: php regex preg-replace-callback


【解决方案1】:

这应该可行:

<?php
$comments   = array();              

$selectors  = preg_replace_callback('~\*(?>(?:(?>([^*]+))|\*(?!\/))*)\*~',
function ($match) use (&$comments) {  //add the variable $comments to the function scope
    $comments[] = $match[0];
    return '';
}, $input);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多