PHP正则表达式;提取WordPress短代码中的第一个匹配ID
有这根绳子PHP正则表达式;提取WordPress短代码中的第一个匹配ID,php,regex,wordpress,extract,shortcode,Php,Regex,Wordpress,Extract,Shortcode,有这根绳子 $string = '[gallery link="file" ids="501,502,503,504,505,506,507,508,509"]'; 如何提取ids中的第一个id 到目前为止,我已经成功地提取了所有的ID,然后使用split $output = preg_match_all('/\[gallery.+ids=[\'"](.+?)[\'"]\]/', $string, $matches); list($extracted) = split(',', $matche
$string = '[gallery link="file" ids="501,502,503,504,505,506,507,508,509"]';
如何提取ids中的第一个id
到目前为止,我已经成功地提取了所有的ID,然后使用split
$output = preg_match_all('/\[gallery.+ids=[\'"](.+?)[\'"]\]/', $string, $matches);
list($extracted) = split(',', $matches[1][0]);
只使用正则表达式肯定有更简单的方法,对吗
谢谢:)您可以尝试下面的正则表达式来匹配id中的第一个id
\[gallery.+ids=\"\K[^,]*
或
你的PHP代码是
<?php
$string = '[gallery link="file" ids="501,502,503,504,505,506,507,508,509"]';
$pattern = '~\[gallery.+ids="\K([^,]*)~';
if (preg_match($pattern, $string, $m)) {
$yourmatch = $m[0];
echo $yourmatch;
}
?> //=> 501
/=>501
如何提取ids中的第一个id
从索引1中获取匹配的组
\bids="(\d+)
这是
或者试试看
(?无论你在这里尝试什么,看起来都很奇怪。你不需要正则表达式来获取短码参数。而是使用Wordpress的默认内置函数
来自codex.wordpress.org的示例:
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
见:
更新–获取第一个ID:
// [gallery link="file" ids="501,502,503,504,505,506,507,508,509"]
function gallery_shortcode( $atts ) {
$atts = shortcode_atts( array(
'link' => 'file',
'ids' => array(),
), $atts );
$ids = explode( ',', $atts );
// strip the first ID from the array…
$first_id = array_shift( $ids );
// …or just select it
$first_id = $ids[0];
return $first_id;
}
add_shortcode( 'gallery', 'gallery_shortcode' );
太快了!谢谢我没有像你的评论中提到的那样尝试添加短代码。add\u shortcode()
我正在尝试解析插件嵌入到帖子内容中的短代码;$post->post\u content
。上面接受的解决方案很好,谢谢:)@numediawebadd_shortcode
已经完成了所有的解析——这就是这个函数的目的;知道如何使用add_shortcode()
从[gallery link=“file”id=“501504507508509”
提取第一个id吗?我需要在运行此方法之前的id,以便创建条件CSS并将其正确嵌入头部
$re = "/(?<=\\bids=\\")\\d+/";
$str = "[gallery link=\"file\" ids=\"501,502,503,504,505,506,507,508,509\"]";
preg_match_all($re, $str, $matches);
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
// [gallery link="file" ids="501,502,503,504,505,506,507,508,509"]
function gallery_shortcode( $atts ) {
$atts = shortcode_atts( array(
'link' => 'file',
'ids' => array(),
), $atts );
$ids = explode( ',', $atts );
// strip the first ID from the array…
$first_id = array_shift( $ids );
// …or just select it
$first_id = $ids[0];
return $first_id;
}
add_shortcode( 'gallery', 'gallery_shortcode' );