0

I have a string like WordPress shortcodes and need to extract the attributes. :
[prefix action="foo" class="bar"][/prefix]

I need to keep exactly this structure that means I can't i.e. remove quotes to become action=foo

right now i used WordPress regex patterns:

// Grabs [prefix foo="bar"][/prefix] from the $content
$pattern = '/\[(\[?)(' . PREFIX . ')(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\2\])[^\[]*+)*+)\[\/\2\])?)(\]?)/';
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

this is the result:

Array
 (
     [0] => [prefix action="foo" class="bar"][/prefix]
     [1] => 
     [2] => prefix
     [3] =>  action="foo" class="bar"
     [4] => 
     [5] => 
     [6] => 
 )

Then I Loop through regex matches

foreach( $matches as $block )
    {
    /*
     * I'm not working on WordPress platform, 
     * But I used function shortcode_parse_atts
     */
    $attr = shortcode_parse_atts( $block[3] );

results:

Array
(
    [action] => "foo"
    [class] => "bar"
)

and in the end extract($attr). but as you can see $class and $action values are between double quotes. so i need to get ride of those quotes.

In short:
I want $class = "bar" becomes $class = bar

In case you think why i don't use str_replace or preg_replace, I did but it did not removed quotes somehow ( which i don't understand why )

4

2 回答 2

1

这是你的属性数组;$array如您print_r()在问题中的输出所示:

Array (
    [action] => "foo"
    [class] => "bar"
)

print_r()除非实际上有引号作为值的一部分,否则不输出引号,在这种情况下显然存在引号。要删除我们可以使用的引号str_replace()和这样的array_map()函数:

$clean = array_map(function($item) {
    return str_replace("\"", "", $item);
}, $array);

print_r($clean);

然后我们得到:

Array (
    [action] => foo
    [class] => bar
)
于 2013-07-24T11:37:51.837 回答
0

如果你有这样的事情,

$array = array ( "action" => "\"foo\"", "class" => "\"bar\"" );

然后你可以使用(删除引号)

 $arr = array_map(function($i){ 
    return trim($i, '"'); 
}, $array);

但是,我认为,要么我误解了数组,要么你只是误解了数组,这就是数组的工作方式,看看这个(如果你有这样的数组)

$array = array ( "action" => "foo", "class" => "bar" );
print_r($array);

结果是:

Array
(
    [action] => foo
    [class] => bar
)

现在看看这个

$arr = array_map(function($i){ 
    return trim($i, '"'); 
}, $array);
print_r($arr);

结果是:

Array 
(
    [action] => foo
    [class] => bar 
)

或者您可以将其测试为

extract($array);
echo $class; // barArray

因此,在这种情况下quotes,是数组的一部分来包装string值,并且在输出中,quotes将不可见。

于 2013-07-24T12:26:50.083 回答