0

I need a preg function which do the following job for following string-

string = {my_special_shortcode_name var1='some_var1' var2='some_var2' var3='some_var3'}

and the extracted string must look like-

Array( 'var1' =>  'some_var1',
       'var2' => 'some_var2',
       'var3' => 'some_var3'
)

Obviously I need the some pref function, but I have tried separating the string based on space formatting, but when I include spaces in any parameter of var1/var2/var3, for ex-

When I given this input instead-

string = {my_special_shortcode_name var1='some var1' var2='some_var2' var3='some_var3'}

NOTE THE SPACE IN SOME VAR1 (INSTEAD OF SOME_VAR1)

The following output is obtained-

Array( 'var1' =>  'some',
       'var1' => 'var2',
       'some_var2' => 'var3'
)

So I need a function which separate the string based on space outside the "" , not the space within "" .

Any idea how?

EDIT: I have successfully extracted the string into array. Problem lies in URL containing '?' which makes the separate string within "". So now, I need someone to suggest how to escape '?' and separate string into array?

4

4 回答 4

0

我会使用preg_match_all函数,如:

$str = "{my_special_shortcode_name var1='some var1' var2='some_var2' var3='some_var3'}";
preg_match_all("~(\w+)\s*=\s*'([^']+)'~", $str, $m);
print_r($m);

输出:

Array
(
    [0] => Array
        (
            [0] => var1='some var1'
            [1] => var2='some_var2'
            [2] => var3='some_var3'
        )

    [1] => Array
        (
            [0] => var1
            [1] => var2
            [2] => var3
        )

    [2] => Array
        (
            [0] => some var1
            [1] => some_var2
            [2] => some_var3
        )

)
于 2014-01-01T10:50:03.507 回答
0

你总是可以把它从/[^\\]' /. 所以这会得到'_,但不是\'_(其中 _ 是你的空间),这样你就可以在撇号的值中包含一个转义字符。

于 2013-03-15T18:01:15.040 回答
0
$string = "{my_special_shortcode_name var1='http://stackoverflow.com/q/15438976/1020526?test' var2='some_var2' var3='some_var3'}";
preg_match_all("/\b(\w+)='([^']+)'/", $string, $matches);
$arr = array_combine($matches[1], $matches[2]); // first captured groups as key, and the second as the array values
print_r($arr);

输出

Array
(
    [var1] => http://stackoverflow.com/q/15438976/1020526?test
    [var2] => some_var2
    [var3] => some_var3
)
于 2014-01-02T12:29:37.710 回答
0

你可以像 /var[\d]+='([\w ]+)'/ 这样的正则表达式

$pattern = "/var[\d]+='([\w ]+)'/";
$subject = "{my_special_shortcode_name var1='some var1' var2='some_var2' var3='some_var3'}";
preg_match_all( $pattern, $subject, $matches);

$matches 将填充:

array (
  0 => 
  array (
    0 => 'var1=\'some var1\'',
    1 => 'var2=\'some_var2\'',
    2 => 'var3=\'some_var3\'',
  ),
  1 => 
  array (
    0 => 'some var1',
    1 => 'some_var2',
    2 => 'some_var3',
  ),
)
于 2013-03-15T18:48:46.143 回答