Regplace,带有php的正则表达式不起作用


Regplace , regex with php doesnt work

    <?php
        $target="This is a test | dont present me!";
        $pattern="/'| (.*?)/";
       $target=  preg_replace($pattern, '', $target);
        echo $target;
    ?>

我试图摆脱从管道向右的所有内容......但正则表达式不起作用。 我错过了什么?

尝试以下操作:

$pattern="/'| .*/";

根本不需要括号,因为您不会重复它,也不会在替换中重复使用。 而问号在*之后是多余的,两者都是量词。 (@wrikken的评论是对的,*?*的懒惰版本。

试试这个:

<?php
    $target="This is a test | dont present me!";
    $pattern="/'|.*/";
    $target=  preg_replace($pattern, '', $target);
    echo $target;
?>

为什么你的模式中有?

如果您真的不需要分组,请尝试使用/'|(.*)/甚至只是/'|.*/