dongpao1921 2017-02-13 19:16
浏览 104
已采纳

仅输出PHP数组括号中不包含HTML标记的值

Here is a sample PHP array that explains my question well

$array = array('1' => 'Cookie Monster (<i>eats cookies</i>)',
               '2' => 'Tiger (eats meat)',
               '3' => 'Muzzy (eats <u>clocks</u>)',
               '4' => 'Cow (eats grass)');

All I need is to return only values that don't contain any tag enclosed with parentheses from this array:

- Tiger (eats meat)
- Cow (eats grass)

For this I'm going to use the following code:

$array_no_tags = preg_grep("/[A-Za-z]\s\(^((?!<(.*?)(\h*).*?>(.*?)<\/\1>).)*$\)/", $array);
foreach ($array_no_tags as $a_n_t) {echo "- ".$a_n_t."<br />";}

Assuming that [A-Za-z] may be whoever, \s is a space, \( is the opening parenthesis, ^((?! is start of the tag denial statement, <(.*?)(\h*).*?>(.*?)<\/\1> is the tag itself, ).)*$ is end of the tag denial statement and \) is the closing parenthesis.

Nothing works.

print_r($array_no_tags); returns empty array.

  • 写回答

2条回答 默认 最新

  • dpzyd8865 2017-02-13 19:33
    关注

    You could use the following expression to match strings with HTML tags inside of parentheses:

    /\([^)]*<(\w+)>[^<>]*<\/\\1>[^)]*\)/
    

    Then set the PREG_GREP_INVERT flag to true in order to only return items that don't match.

    $array_no_tags = preg_grep("/\([^)]*<(\w+)>[^<>]*<\/\\1>[^)]*\)/", $array, true);
    

    Explanation:

    • \( - Match the literal ( character
      • [^)]* - Negated character class to match zero or more non-) characters
      • <(\w+)> - Capturing group one that matches the opening element's tag name
      • [^<>]* - Negated character class to match zero or more non-<> characters
      • <\/\1> - Back reference to capturing group one to match the closing tag
      • [^)]* - Negated character class to match zero or more non-) characters
    • \) - Match the literal ) character

    If you don't care about the parentheses around the element tag, then you could also just use the following simplified expression:

    /<(\w+)>[^<>]+<\/\\1>/
    

    And likewise, you would use:

    $array_no_tags = preg_grep("/<(\w+)>[^<>]+<\/\\1>/", $array, true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部