PHP新线阵,向前看

PHP new line array, look ahead

我有以下代码例程,它是 preg_match ing xml 元素并打印这些元素的属性。

但是,在某些标签中,内容没有出现在一行中(SCRIPT 标签),因此无法匹配。

我想知道如何向前看并收集所有行直到结束标记“/>”?

是否可以在 preg_match 中的某处使用 @ 字符以允许换行?

我什至不确定如何解决这个问题。我做了一个 PHP 沙箱,所以可以在线测试代码:

http://sandbox.onlinephpfunctions.com/code/f96daef33fb49179eee30250ded81af6a8e5c567

如果我删除脚本标记中的所有数据,除了第一行,然后它会正确输出数组。

$file = '    <TOPTAG class="Menu" text="FCLPHP" >
        <TAG1 name="contain=" />
        <SCRIPT name="check()" script="if(B3||B4||B5 == 1){
        do(ABC,0);
        do(BCD,1);" />
    </WINDOW>
';

//split the string into an array based on new line
$lines = explode("\n", $file);

//count the number of lines
$linesLength = count($lines);

for($index = 0; $index < $linesLength; $index++){

    //reads all element atrributes from the TOPTAG element
    $reads = element_attributes('TOPTAG',$lines[$index]);   

    //reads all element atrributes from the SCRIPT element
    $scripts = element_attributes('SCRIPT',$lines[$index]);

    //prints the script tag attributes
    print_r($scripts); 
}


function element_attributes($element_name, $xml) {
    if ($xml == false) {
        return false;
    }
    // Grab the string of attributes inside an element tag.
    $found = preg_match('#<'.$element_name.
            '\s+([^>]+(?:"|\'))\s?/?>#',
            $xml, $matches);
    if ($found == 1) {
        $attribute_array = array();
        $attribute_string = $matches[1];
        // Match attribute-name attribute-value pairs.
        $found = preg_match_all(
                '#([^\s=]+)\s*=\s*(\'[^<\']*\'|"[^<"]*")#',
                $attribute_string, $matches, PREG_SET_ORDER);
        if ($found != 0) {
            // Create an associative array that matches attribute
            // names to attribute values.
            foreach ($matches as $attribute) {
                $attribute_array[$attribute[1]] =
                        substr($attribute[2], 1, -1);
            }
            return $attribute_array;
        }
    }
    // Attributes either weren't found, or couldn't be extracted
    // by the regular expression.
    return false;
}

您的正则表达式跨多行运行。问题是你一次只在一行中使用它,所以它永远看不到延续。不要将文件拆分成行,只需将其作为单个字符串使用即可。

$reads = element_attributes('TOPTAG',$file);
$scripts = element_attributes('SCRIPT',$file);