我的帖子里有这样的代码:
[quick_view product_id="10289" type="button" label="Quick View"]我希望在一个函数中有一个数字"10289“匹配任何数字:
if (stripos($post-> post_content, '[quick_view product_id="XXXX" type="button" label="Quick View"]') !== false) 如何才能取代"XXXX“来接受所有的数字?
完整片段:
function conditionally_add_scripts_and_styles($posts){
if (empty($posts)) return $posts;
$shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued
foreach ($posts as $post) {
if (stripos($post-> post_content, '[quick_view product_id="XXXX" type="button" label="Quick View"]') !== false) {
$shortcode_found = true; // bingo!
break;
}
}
if ($shortcode_found) {
// enqueue here
wp_enqueue_style('my-style', '/woocommerce.css');
wp_enqueue_script('my-script', '/script.js');
}
return $posts;
}谢谢。
发布于 2017-04-16 07:23:48
试试这个,希望它能正常工作。
Regex: /product_id\s*\=\s*\"\d+\"/这个正则表达式将查找product_id="<->"之间的数字
示例:
product_id="xxAbcxx"将被拒绝。
product_id="1212121"将被接受。
if(preg_match("/product_id\s*\=\s*\"\d+\"/", $post->post_content))
{
echo "Accepted";
}完整的代码如下所示。
function conditionally_add_scripts_and_styles($posts)
{
if (empty($posts))
return $posts;
$shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued
foreach ($posts as $post)
{
if(preg_match("/product_id\s*\=\s*\"\d+\"/", $post->post_content))
{
$shortcode_found = true;
break;
}
}
if ($shortcode_found)
{
// enqueue here
wp_enqueue_style('my-style', '/woocommerce.css');
wp_enqueue_script('my-script', '/script.js');
}
return $posts;
}发布于 2017-05-08 23:26:27
Sahil的答案包括不必要的代码位数和次优正则表达式。为了获得最好的性能,读者应该使用以下方法:
function conditionally_add_scripts_and_styles($posts){
foreach($posts as $post){
if(preg_match('/product_id="\d/',$post->post_content)){
wp_enqueue_style('my-style','/woocommerce.css');
wp_enqueue_script('my-script','/script.js');
break;
}
}
return $posts;
}我的回答和萨希尔的有什么区别?
empty()循环之前的foreach()条件是不必要的,因为即使数组是空的,foreach也不会迭代一次。$shortcode_found的每一次声明/使用都是不必要的。=,这是不必要的,并教会了一个不必要的习惯。product_id的值没有必要,因为如果只有一个数字,条件应该正确地返回true结果。因为OP已经指出产品id的格式是完全数字的,所以不需要检查整个值。如果存在对全部值的关注,那么/product_id="\d+"/就能做到这一点。https://stackoverflow.com/questions/43434762
复制相似问题