我正在开发一个函数,该函数将帖子的标题与(我网站中产品的)标题列表进行比较。
这是为了在我自己的网站上建立一个简单的广告系统,它可以查看当前帖子的标题,并将其与我网站上产品的标题进行比较。
如果匹配,系统需要从帖子标题中剪切产品标题字符串,并删除其余部分。
示例:
当前标题:一辆全新的山地自行车!
标题列表:
- 冰箱
- 表
- 山地自行车
- Book
- 笔记本电脑
因此,我的系统需要关注标题:"一辆全新的山地自行车!",将其循环到产品标题中,如果它与"山地自行车"匹配,则需要停止循环并切断"一辆崭新的"。
所以我只有一句话:"山地自行车"。
我的代码(我在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;
}
}
}
多亏了MoshMage,这段代码解决了我的问题。$match
变量现在包含产品名称。
$current_title = get_the_title();
$titles = new WP_Query( array( 'post_type' => 'products', 'posts_per_page' => -1 ) );
if( $titles->have_posts() ) {
while( $titles->have_posts() ) {
$titles->the_post();
$title = get_the_title();
if( preg_match('/' . $title . '/i', $current_title, $matched ) ) {
$match = $matched[0];
}
}
}
strpos()区分大小写,因此在"全新山地自行车!"中找不到"Mountainbike"。
将您的条件更改为:
if( stripos( $current_title, $title) !== false ) {
- 使用不区分大小写的stripos
- 也可以使用==false,因为如果你没有,并且字符会在位置0上找到,那么你会认为没有匹配-有关更多信息,请参阅php手册的"返回值"部分
完整代码:
$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( stripos($current_title, $title) !== false ) {
// Here I need to cut the product from the title
$found = $title;
break;
}
}
}