【问题标题】:Get color codes in string获取字符串中的颜色代码
【发布时间】:2014-09-27 20:03:31
【问题描述】:

我有一个类似

的字符串
<font color="#ffffff">Heippa </font><b><i><u><font face="Calibri" color="#e71818">rallaa</font></u></i></b>

我需要将所有颜色代码分隔在一个数组中

['#ffffff','#e71818']

有没有简单的方法来做到这一点。我知道您可以使用 strrchr 查找所有 # 标记和 substr($color, 0, 7),但这只会打印出最后找到的标记。

感谢您的建议。

【问题讨论】:

  • 看看使用正则表达式来匹配它们:php.net/manual/en/function.preg-match-all.php
  • 您可以使用preg_match_all 搜索以# 开头并后跟6 个字符、字母a-f 和数字0-9 的字符串。
  • 布埃诺!谢谢你。没想到。
  • 你们中有人想过&lt;font color="blue"&gt;color="#123" 吗?使用DOMDocumentSimpleXML....

标签: php


【解决方案1】:
 $input='<font color="#ffffff">Heippa </font><b><i><u><font face="Calibri" color="#e71818">rallaa</font></u></i></b>';   
 preg_match_all("/#[0-9a-f]{6}/i", $input, $output);
 print_r($output);

【讨论】:

    【解决方案2】:

    此示例适用于您的 HTML:

    <?php
    
    $html = '<font color="#ffffffa">Heippa </font><b><i><u><font face="Calibri" color="#e71818">rallaa</font></u></i></b>';
    
    $matches = array();
    
    $found = preg_match_all('/#(?:[0-9a-f]{3}){1,2}/i', $html, $matches, PREG_PATTERN_ORDER);
    
    if ($found) {
    
        $result = array();
    
        foreach ($matches[0] as $m) {
            // Key $m for unique result:
            $result[$m] = $m;
        }
    
        print_r($result);
    
    }
    

    但不适用于此 HTML:

    color="#0123456789abcdef"  // will match #012345
    color="red"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-12
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 2013-05-24
      相关资源
      最近更新 更多