使用preg_replace删除除引号

时间:2016-03-09 16:18:12

标签: php regex preg-replace

我有以下短代码,我正在尝试运行preg_replace,以获取标题值。

[tab title="Emergency Contact" important="true"]

目前,我使用以下过滤器:

$sanitized_title = $tab_title ? preg_replace("/[\”\"\’\']*|(?:’|”)*\]/i", "", preg_replace("/\[tab *title=[\”\"\’\']*|(?:’|”)*/i", "", $tab_title[0])) : __("Open Tab");

这会返回“Emergency Contact important = true”,这不是我需要的。我基本上试图获得$title = "Emergency Contact"$important = "true"之类的东西。

如何修改我的正则表达式字符串来执行此操作?我真的不知道我正在用正则表达式做什么,很惊讶我已经达到了我的目标。

另外需要注意的是,并非每个短代码都有两个值。一些替代的例子:

[tab]
[tab title="Emergency Contact"]
[tab important="true"]

3 个答案:

答案 0 :(得分:2)

您正在寻找类似的东西:

<?php

$string = 'some gibberish here [tab title="Emergency Contact" important="true"] some additional info here';

$regex = '~
            (?:\[tab\s         # looks for [tab + whitespace literally
            |                  # or
            (?!\A)\G\s)        # (?!\A) = negative lookahead
                               # to make sure the following is not the start
                               # of the string
                               # \G matches at the end of the previous match
            (?P<key>\w+)       # match a word character greedily to group "key"
            =
            "(?P<value>[^"]+)" # " + anything not " + ", save this to group "value"
         ~x';                  # verbose modifier
preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
    echo "Key: {$match['key']}, Value: {$match['value']}\n";
/* output:
Key: title, Value: Emergency Contact
Key: important, Value: true
*/
?>

这将查找[tab]标记中的所有键/值对,请参阅a demo on regex101.com 另外demo can be found on ideone.com

答案 1 :(得分:1)

  

我基本上想要获得类似$ title =&#34; Emergency Contact&#34;和$ important =&#34; true&#34;。

试试[a-z]+="[A-Za-z ]+"

这是最简单的正则表达式,它将匹配以下格式的模式。

Characters from a-z="Characters from A-Z and a-z including space"

Regex101 Demo

答案 2 :(得分:0)

您可以使用“preg_match_all”获取短代码属性。

<?php
//string
$qoute_string = '[tab title="Emergency Contact" important="true"]';

//pattern
$pattern = '/ (.*?)="(.*?)"/';

$tab_attr = array();
//get the attributes.
if(preg_match_all($pattern, $qoute_string, $data)) {
    foreach ($data[0] as $key => $val) {
        $variable = explode("=",$val);
        $tab_attr[trim($variable[0])] = str_replace('"', "", $variable[1]);
    }
}

//see the results
print_r($tab_attr);
echo '<br />';

//title
echo $tab_attr['title'];
echo '<br />';

//important
echo $tab_attr['important'];
?>