我正在编写一个脚本来查找内容中第一次出现以下短代码,然后获取短代码的url参数。
短代码看起来像这样
[soundcloud url="http://api.soundcloud.com/tracks/106046968"]
我现在所做的是
$pattern = get_shortcode_regex();
$matches = array();
preg_match("/$pattern/s", get_the_content(), $matches);
print_r($matches);
,结果看起来像
Array (
[0] => [soundcloud url="http://api.soundcloud.com/tracks/106046968"]
[1] =>
[2] => soundcloud
[3] => url="http://api.soundcloud.com/tracks/106046968"
[4] =>
[5] =>
[6] =>
)
这是我需要短代码
参数的url的字符串$html = 'Our good homies <a href="https://www.facebook.com/yungskeeter">DJ Skeet Skeet aka Yung Skeeter</a> & <a href="https://www.facebook.com/WaxMotif">Wax Motif</a> have teamed up to do a colossal 2-track EP and we\'re getting the exclusive sneak-premiere of the EP\'s diabolical techno b-side called "Hush Hush" before its released tomorrow on <a href="https://www.facebook.com/dimmakrecs">Dim Mak Records</a>!
[soundcloud url="http://api.soundcloud.com/tracks/104477594"]
<a href="https://www.facebook.com/WaxMotif">Wax Motif</a> have teamed up to do a colossal 2-track EP and we\'re getting the exclusive sneak-premiere of the EP\'s diabolical techno b-side called "Hush Hush" before its released tomorrow on <a href="https://www.facebook.com/dimmakrecs">Dim Mak Records</a>!
';
我想这不是最好的方法。如果可以指导我们如何做到这一点那么它会很棒。基本上我想从内容中提取第一次出现的soundcloud url。
答案 0 :(得分:1)
所以这就是我提出的:
preg_match('~\[soundcloud\s+url\s*=\s*("|\')(?<url>.*?)\1\s*\]~i', $input, $m); // match
print_r($m); // print matches (groups) ...
$url = isset($m['url']) ? $m['url']:''; // if the url doesn't exist then return empty string
echo 'The url is : ' . $url; // Just some output
让我们解释正则表达式:
~ # set ~ as delimiter
\[soundcloud # match [soundcloud
\s+ # match a whitespace 1 or more times
url # match url
\s* # match a whitespace 0 or more times
= # match =
\s* # match a whitespace 0 or more times
("|\') # match either a double quote or a single quote and put it in group 1
(?<url>.*?) # match everything ungreedy until group 1 is found and put it in a named group "url"
\1 # match what was matched in group 1
\s* # match a whitespace 0 or more times
\] # match ]
~ # delimiter (end expression)
i # set the i modifier, which means match case-insensitive