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 )
This is your attributes array; $array
as shown by your print_r()
output in the question:
Array (
[action] => "foo"
[class] => "bar"
)
print_r()
doesnt output quotes unless there actually are quotes as part of the values, which there clearly is in this case. To remove the quotes we can use str_replace()
and the array_map()
function like this:
$clean = array_map(function($item) {
return str_replace("\"", "", $item);
}, $array);
print_r($clean);
Then we get:
Array (
[action] => foo
[class] => bar
)
If you have something like this,
$array = array ( "action" => "\"foo\"", "class" => "\"bar\"" );
Then you can use (to remove the quotes)
$arr = array_map(function($i){
return trim($i, '"');
}, $array);
But, I think, either I'm miss-understanding or you are just miss-understanding the array, it's the way the array works, look at this (if you have an array like this)
$array = array ( "action" => "foo", "class" => "bar" );
print_r($array);
Result is :
Array
(
[action] => foo
[class] => bar
)
Now look at this
$arr = array_map(function($i){
return trim($i, '"');
}, $array);
print_r($arr);
Result is :
Array
(
[action] => foo
[class] => bar
)
Or you can test it as
extract($array);
echo $class; // barArray
So, in this case quotes
are part of the array to wrap the string
value and in the output, the quotes
won't be visible.