【发布时间】:2014-10-19 12:49:51
【问题描述】:
我正在开发一个功能,它将帖子的标题与标题列表(我网站中的产品)进行比较。
它用于在我自己的网站上构建一个简单的广告系统,它会查看当前帖子的标题并将其与我网站中产品的标题进行比较。
如果匹配,系统需要从帖子标题中剪切产品标题字符串并删除其余部分。
示例:
当前标题:全新的山地自行车!
标题列表:
- 冰箱
- 表
- 山地自行车
- 书籍
- 笔记本电脑
所以我的系统需要观看标题:“全新的山地自行车!”,通过产品标题循环它,如果匹配“山地自行车”,它需要停止循环并切断“全新的”。
所以我只有字符串:“mountainbike”。
我的代码(我在 Wordpress 中构建):
$current_title = get_the_title(); // "A brand new mountainbike!"
$titles = new WP_Query( array( 'post_type' => 'products', 'posts_per_page' => 100 ) ); // List of titles
if( $titles->have_posts() ) {
while( $titles->have_posts() ) {
$titles->the_post();
$title = get_the_title(); // The product title from the list
if( strpos( $current_title, $title ) ) {
// Here I need to cut the product from the title
$found = strpos( $current_title, $title );
break;
}
}
}
【问题讨论】:
-
尝试使用 stripos(),它不区分大小写...并将其与 !== false 运算符匹配,因为返回 0 应该是正匹配
-
感谢 cmets。我会努力的!
-
或者您可以尝试使用preg_match('/mountainbike/i',$current_title,$match) 和
$match将保留您匹配的密钥。注意 i 使其不区分大小写 -
谢谢,这可行,但是 $match 返回一个数组?
标签: php string wordpress loops strpos