Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/249.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 在content-Wordpress中提取短代码参数_Php_Wordpress - Fatal编程技术网

Php 在content-Wordpress中提取短代码参数

Php 在content-Wordpress中提取短代码参数,php,wordpress,Php,Wordpress,想想下面这样的帖子内容: [shortcode a="a_param"] ... Some content and shortcodes here [shortcode b="b_param"] .. Again some content here [shortcode c="c_param"] 我有一个接受3个或更多参数的短代码。 我想知道短码在数组中的内容及其参数中使用了多少次 array ( [0] => array(a => a_param, b=> null, c=

想想下面这样的帖子内容:

[shortcode a="a_param"]
... Some content and shortcodes here
[shortcode b="b_param"]
.. Again some content here
[shortcode c="c_param"]
我有一个接受3个或更多参数的短代码。 我想知道短码在数组中的内容及其参数中使用了多少次

array (
[0] => array(a => a_param, b=> null, c=>null),
[1] => array(a => null, b=> b_param, c=>null),
[2] => array(a => null, b=> null, c=>c_param),
)
我需要在内容过滤器、wp头过滤器或类似的东西中执行此操作

我该怎么做

谢谢,

In wordpress函数返回正则表达式,用于搜索文章中的短代码

$pattern = get_shortcode_regex();
然后preg_将模式与post内容匹配

if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
如果返回true,则提取的短代码详细信息保存在$matches变量中

试试看

global $post;
$result = array();
//get shortcode regex pattern wordpress function
$pattern = get_shortcode_regex();


if (   preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches ) )
{
    $keys = array();
    $result = array();
    foreach( $matches[0] as $key => $value) {
        // $matches[3] return the shortcode attribute as string
        // replace space with '&' for parse_str() function
        $get = str_replace(" ", "&" , $matches[3][$key] );
        parse_str($get, $output);

        //get all shortcode attribute keys
        $keys = array_unique( array_merge(  $keys, array_keys($output)) );
        $result[] = $output;

    }
    //var_dump($result);
    if( $keys && $result ) {
        // Loop the result array and add the missing shortcode attribute key
        foreach ($result as $key => $value) {
            // Loop the shortcode attribute key
            foreach ($keys as $attr_key) {
                $result[$key][$attr_key] = isset( $result[$key][$attr_key] ) ? $result[$key][$attr_key] : NULL;
            }
            //sort the array key
            ksort( $result[$key]);              
        }
    }

    //display the result
    print_r($result);


}

如果属性值中有空格,则可能的重复将不起作用,因为str_replace()也会影响这些空格。@ChrisJ.Zähler谢谢你指出我的错误。我会很快更正并更新答案非常感谢你