
在php开发中,我们经常需要解析特定格式的字符串,例如wordpress短代码或自定义配置字符串,从中提取出属性(键)及其对应的值。一个典型的例子是:
$shortcode = '[csvtohtml_create include_rows="1-10" debug_mode="no" source_type="guess" path="largecsv" source_files="test?output=csv" csv_delimiter="," ]';
这里的挑战在于,属性值可能包含特殊字符(如等号=或问号?)或空格,并且这些值被双引号包围。如果采用简单的字符串分割方法,很容易导致数据解析不完整或错误。例如,source_files="test?output=csv"中的output=csv部分,如果处理不当,可能会被错误地截断。
初学者可能会尝试使用preg_split结合explode来解析。例如:
$args = preg_split('/"[^"]+"(*SKIP)(*F)|\h+/', $shortcode);
$attrs = [];
foreach( $args as $item ) {
    if ( strpos( $item , '=' ) !== false ) {
        $sep = explode( '=', $item );
        $key = $sep[0];
        $value = $sep[1];
        $attrs[$key] = str_replace( '"', '', $value );
    }
}这种方法的问题在于,preg_split虽然能够避免在引号内部进行分割,但在后续使用explode('=',$item)时,如果属性值内部包含等号(如test?output=csv),explode会将其在第一个等号处分割,导致source_files的值被错误地解析为"test?output",丢失了=csv部分。因此,对于此类复杂解析,我们需要更健壮的方法。
一种更可靠的方法是使用preg_match_all来精确匹配所有属性-值对,然后利用parse_str函数将这些对转换为关联数组。
立即学习“PHP免费学习笔记(深入)”;
首先,我们定义一个正则表达式来匹配key="value"形式的字符串。
$shortcode = '[csvtohtml_create include_rows="1-10" debug_mode="no" source_type="guess" path="largecsv" source_files="test?output=csv"  csv_delimiter="," ]';
// 正则表达式:
// [^\s=]+    匹配一个或多个非空白且非等号的字符(作为键)
// ="         匹配字面量 ="
// "[^"]*"    匹配一个双引号,后跟零个或多个非双引号字符,再跟一个双引号(作为值)
preg_match_all('/[^\s=]+="[^"]*"/', $shortcode, $matches);
// $matches[0] 将包含所有匹配到的完整键值对字符串,例如 "include_rows="1-10"", "debug_mode="no"" 等
print_r($matches[0]);
/*
Array
(
    [0] => include_rows="1-10"
    [1] => debug_mode="no"
    [2] => source_type="guess"
    [3] => path="largecsv"
    [4] => source_files="test?output=csv"
    [5] => csv_delimiter=","
)
*/parse_str()函数通常用于解析URL查询字符串。我们可以将preg_match_all得到的所有键值对用&符号连接起来,模拟一个查询字符串,然后传递给parse_str()。
$shortcode = '[csvtohtml_create include_rows="1-10" debug_mode="no" source_type="guess" path="largecsv" source_files="test?output=csv"  csv_delimiter="," ]';
preg_match_all('/[^\s=]+="[^"]*"/', $shortcode, $matches);
// 将匹配到的所有键值对用 '&' 连接起来,形成一个查询字符串
$queryString = implode('&', $matches[0]);
// 使用 parse_str 解析查询字符串到数组
parse_str($queryString, $attributes);
print_r($attributes);
/*
Array
(
    [include_rows] => "1-10"
    [debug_mode] => "no"
    [source_type] => "guess"
    [path] => "largecsv"
    [source_files] => "test?output=csv"
    [csv_delimiter] => ","
)
*/通过这种方法,我们成功地将所有属性及其值(包括值内部的等号)提取到了一个关联数组中。注意,此时值仍然包含双引号。
如果你希望在解析的同时自动去除值的双引号,并且处理更像INI文件格式的键值对,那么parse_ini_string是一个非常优雅的选择。
parse_ini_string()函数可以解析INI格式的字符串,它会自动处理键值对,并且对于被引号包围的值,会自动去除引号。
$shortcode = '[csvtohtml_create include_rows="1-10" debug_mode="no" source_type="guess" path="largecsv" source_files="test?output=csv"  csv_delimiter="," ]';
preg_match_all('/[^\s=]+="[^"]*"/', $shortcode, $matches);
// 将匹配到的所有键值对用换行符 '\n' 连接起来,模拟INI文件格式
$iniString = implode("\n", $matches[0]);
// 使用 parse_ini_string 解析INI格式字符串到数组
$attributes = parse_ini_string($iniString);
print_r($attributes);
/*
Array
(
    [include_rows] => 1-10
    [debug_mode] => no
    [source_type] => guess
    [path] => largecsv
    [source_files] => test?output=csv
    [csv_delimiter] => ,
)
*/这种方法不仅代码简洁,而且parse_ini_string自动处理了值的引号,使得最终结果更加干净。
通过结合使用preg_match_all进行模式匹配和parse_str或parse_ini_string进行数据解析,我们可以高效且准确地从复杂字符串中提取属性及其值。parse_ini_string方法尤其简洁,因为它能自动处理值的引号。选择哪种方法取决于你的具体需求:如果需要保留值的引号,parse_str是合适的;如果希望自动去除引号,parse_ini_string则更为便捷。这两种方法都比简单的字符串分割更能适应包含特殊字符的复杂属性值场景。
以上就是PHP:高效解析带引号属性的字符串的详细内容,更多请关注php中文网其它相关文章!
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号