【问题标题】:Warning: preg_match(): Unknown modifier 't'警告:preg_match():未知修饰符 't'
【发布时间】:2014-10-28 22:29:20
【问题描述】:

请帮帮我:

 function getTextBetweenTags($string, $tagname)
 {
    $pattern = "/<$tagname>(.*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
 }

我明白了:

警告:preg_match(): Unknown modifier 't' 

另外,我也试过了:

    $pattern = "~<$tagname>(.*?)<\/$tagname>~";

在这种情况下,我有:

警告:preg_match():编译失败:在偏移 146 处的字符类中范围乱序

当然,我已经尝试过变体

$pattern = "/<".$tagname.">(.*?)<\/".$tagname.">/";

有什么想法吗? )

【问题讨论】:

    标签: php preg-match


    【解决方案1】:

    您需要在 getTextBetweenTags 调用中更改参数的位置。 'abc' 是标签的名称,而不是要搜索的字符串,对吧?

    $html = "<html><body><abc>HELLO</abc></body></html>";
    
    function getTextBetweenTags( $string, $tagname ) {
        preg_match( "/\<{$tagname}\>(.*)\<\/{$tagname}\>/", $string, $matches );
        return $matches[1];
    }
    
    var_dump( getTextBetweenTags( $html, 'abc' ) );
    

    【讨论】:

    • 感谢您的建议,但在这种情况下,我的函数code$content = getTextBetweenTags('abc', $page);工作不正确,而不是标签“abc”中的内容,我在文档 $page 中得到了第一个标签。
    • 编辑了我的答案,对不起,我一开始看错了你的问题。你调用 $content = getTextBetweenTags('abc', $page);而 $content = getTextBetweenTags($page, 'abc');是你需要的。
    • Valentin,非常感谢,但在这种情况下,我得到了 Notice: Undefined offset: 1 in code echo $matches[1]; //标签名 注意:未定义的偏移量:2 in code in line echo $matches[2]; //旧代码中的文本 preg_match( "/\(.*)\/", $tagname, $matches );回声 $matches[1]; //标签名称 echo $matches[2]; //text 在新代码中:注意:Undefined offset: 1 in code return $matches[1];另外,告诉我code NULL(我认为是由于 var_dump)
    • 只需使用我的答案中的实现,我将其更新为接受标签名称作为参数。旧版本不允许这样做。
    • 在新代码中:注意:未定义的偏移量:代码中的 1 返回 $matches[1];另外,显示我的代码 NULL(我认为是由于 var_dump)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-20
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多