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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?