Search code examples
phparraysjsoncurlhtmlspecialchars

Cannot use array_search() when entity has Apostrophes in them


I'm having an issue where I have a list of company's as an array and I am using array_search() to get the Keys from this array to store in a database as an ID.

This works with all of my company's except ones with apostrophes in them! I don't know how array_search() works specifically but I can't find a solution posted online for this.

<?php
$array = array("pipefix", "Housing ltd","o'briens roofing","argos");
$search = "o'briens roofing";

$id = array_search($search, $array);
print_r($id);

This is obviosuly not my exact code, but is the same principle, I am trying to search the array for my company, but if it has an ' in it, it will always return nothing! Any ideas or solutions for this?


Solution

  • The Array i used is pulled from another databases stored information and is posted on an API that i have no control over unfortunately.

    I do not store this my my database, I only store the [ID's] for management and inputs.

    The array pulled is HTML encoded when retrieved.

    I pulled this array from the API using JSON and cUrl. This means when i first get hold of the array values the Apostrophe has been converted to &apos;s.

    I thought using htmlsecialchars_decode() would revert this. Thanks to Ryan Vincent he has shown me the issue is created when it is Pulled using cUrl.

    Unfortunately i can not change this so when the array is created, I now do a str_replace() and simply remove the &apos;s.

    This means once displayed it is technically incorrect. but as this is only being used by a few people it is more efficient to do this than have to do it on the back end for every search.