Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 查找XML中的所有标记及其位置_Php_Regex_Tags - Fatal编程技术网

Php 查找XML中的所有标记及其位置

Php 查找XML中的所有标记及其位置,php,regex,tags,Php,Regex,Tags,是否可以找到字符串中的所有标记及其位置 例如,对于以下文本: #$text = file_get_contents($file); # for the simplicity - see other line: $text = "<tag> sometext <tag2> more text </tag2>"; 据我所知,应使用正则表达式。如果有帮助的话-我知道所有标签的名称。为了简单起见,它们是: <tag>, <tag1>, <

是否可以找到字符串中的所有标记及其位置

例如,对于以下文本:

#$text = file_get_contents($file); # for the simplicity - see other line:
$text = "<tag> sometext <tag2> more text </tag2>";
据我所知,应使用正则表达式。如果有帮助的话-我知道所有标签的名称。为了简单起见,它们是:

<tag>, <tag1>, <tag2>, <tag3>, </tag>, </tag1>, </tag2>, </tag3>

获得所需结果的最佳方法是什么?

您可以使用以下正则表达式:

preg_match_all('@(\</?[a-z0-9]+\>)@', $text, $m);

$tags = array();
foreach ($m[1] as $i => $match) {
  echo "name = " . $m[1][$i] . ", position = " . ($i+1) . "\n";
}
preg\u match\u all('@(\)@',$text,$m);
$tags=array();
foreach($m[1]作为$i=>$match){
echo“name=”.$m[1][$i]”,position=“.($i+1)。“\n”;
}

获取错误:警告:preg_match_all():编译失败:第66行C:\php\www\fetchxml2.php中偏移量13处的括号不匹配一个括号放错位置,现已修复,或再修复一个将标记与数字字符匹配的问题。。很抱歉给您带来不便(这次我执行并验证了代码),这是在命令行上运行的,您无法在浏览器上看到标记和换行符。尝试查看页面源。如果需要在浏览器上渲染它们,则需要将
“\n”
替换为

,将
$m[1][$i]
替换为
htmlentities($m[1][$i])
,这有点棘手。首先,在foreach块之前将
$offset
变量初始化为零。然后将每个块内的
$pos
计算为
strpos($text,$m[1][$i],$offset)
,然后用
$pos
替换
$i+1
,并用
$pos
增加
$offset
preg_match_all('@(\</?[a-z0-9]+\>)@', $text, $m);

$tags = array();
foreach ($m[1] as $i => $match) {
  echo "name = " . $m[1][$i] . ", position = " . ($i+1) . "\n";
}