Search code examples
phpwordpressstringstrpos

Comparing two strings with strpos in Wordpress. Do non-alpha characters cause it to fail?


I'm simply trying to compare two strings to see if they match exactly. If they match, I'm outputting a list. One string is the title of a post (custom post type) from Wordpress, using get_the_title(). The other string is a category from Wordpress. I'm using get_categories(), then a foreach statement and using $category->name.

You can see on this website that for some webinars, it works fine and the list is displayed. But for any webinar with a dash and/or ampersand in the title, it doesn't work.

https://www.financialpoise.com/testwebs/page/2/

I tried doing htmlentities() before comparing strings and it didn't change anything. Below is how I'm doing the compare:

foreach ( $categories as $category ) {
    if(strpos(get_the_title(), $category->name) !== false) {
        //run code here
    }
}

Is there a better/easier way to simply compare two strings to see if they match?

If not, why would a dash or ampersand cause the strpos() function to fail? Theoretically the needle and haystack variables could be in either order because it's looking for a full string in another full string.

Lastly, so you can see in our Wordpress that there is no problem, check out this picture. The title of the post matches the category on that post exactly. That's what I'm trying to compare. Post title and category in Wordpress


Solution

  • You can set their slugs and compare them as a simpler and more secure way.