I am working on a function which compares a title of a post to a list of titles (of products in my website).
It is for building a simple advertise system in my own websites which watches the title of current post and compares it with the titles of the products in my website.
If it gets a match, the system needs to cut the product title string from the post title and removes the rest.
Example:
Current title: A brand new mountainbike!
List of titles:
So my system needs to watch the title: "A brand new mountainbike!", loop it trough the product titles and if it matches "Mountainbike", it needs to stop the loop and cut "A brand new" off.
So I only have the string: "mountainbike".
My code (I build in 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;
}
}
}
Thanks to MoshMage, this piece of code solved my problem. The $match
variable now holds the product name.
$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];
}
}
}