0

在 PHP 中,当我读取数据时,假设数据(字符串块)包含 HTML 特殊字符十进制十六进制代码,例如:
This is a sample string with < œ < and š

我想要的是,如何检测和拆分一段字符串中的十进制十六进制代码(任何特殊字符)?

例如,上面的字符串包含:

  • 两个计数<
  • 一个计数œ
  • 一个计数š

我如何以编程方式检测它(任何 Html 特殊字符的出现)?
(收集的结果作为数组会更好)

4

4 回答 4

3

I think this is what you are after:

$s = 'This is a sample string with œ and š';

$pattern = '/\&#x\d+\;/';

preg_match_all($pattern, $s, $matches);   

var_dump( $matches );

This will output:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(7) "œ"
    [1]=>
    string(7) "š"
  }
}
于 2012-09-08T20:41:53.080 回答
1

您应该使用 preg_match() - http://www.php.net/manual/en/function.preg-match.php与这样的模式 '/&[0-9a-zA-Z]{1,5}; /G'。

[更新]:注意你需要什么实体。这只是&#x[number][number][number];或所有可能的 html 实体(如 <)?

上面我描述了最常见的情况。

于 2012-09-08T20:39:04.330 回答
1

You could use substr and strpos to find &# and skip to the next ;:

$string = "This is a sample string with œ and š"
$hexCodes = array();
while (strlen($string) > 0) {
  if (strpos("&#") > 0) {
    $string = substr($string, strpos("&#"));
    $hex = substr($string, 0, strpos(";") + 1);
    $string = substr($string, strpos(";") + 1);
    array_push($hexCodes, $hex);
  } 
  else { break; }
}
于 2012-09-08T20:42:24.000 回答
-2

If you mean to decode the entities, use html_entity_decode. Here is an example:

<?php
$a = "I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt;";

$b = html_entity_decode($a);

echo $b; // I'll "walk" the <b>dog</b> now
?>
于 2012-09-08T20:33:05.747 回答