dongpao1921 2017-02-14 03: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-14 03: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条)

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入