1

I have the following PHP function which automatically links people's names in a string that are already in the people database. The problem is names that are already linked in the string are double linked. How can I get around this problem?

$str = '<a href="">John T. Smith.</a>';

echo LinkPeopleInString($str);

output  <a href=""><a href="">John T. Smith.</a></a>



function LinkPeopleInString($input_string){

    $connector = $this->DB();

    $sql = $connector->query("SELECT person_url_name, person_first, person_middle, person_last, person_suffix 
                              FROM people WHERE person_draft = 0 AND person_active = 1");
    if(!$sql){
        return $input_string;
    }

    $people_array = array();

    while($row = $connector->fetchArray($sql)){
        $person_url_name = $row['person_url_name'];
        $people_array[$person_url_name] = $this->FormatName($row['person_first'], $row['person_middle'], $row['person_last'], $row['person_suffix']);
    }

    foreach($people_array as $url => $person){
        $input_string = str_replace($person, sprintf('<a href="'.SITE_URL.'/'.PEOPLE_DIRECTORY.'/%s">%s</a>',$url,$person),$input_string);
    }

    return $input_string;

}
Jeff
  • 103
  • 10
  • Maybe do a `preg_match` or something right before calling this function to see if the string is already linked ? – Maximus2012 Sep 08 '15 at 20:19
  • You might need to combine your function logic with that in this question/answer: http://stackoverflow.com/questions/9623007/check-if-a-string-is-a-url – Maximus2012 Sep 08 '15 at 20:20
  • Based on the answers in that question, using `filter_var()` might be even better solution. – Maximus2012 Sep 08 '15 at 20:21
  • I may be missing something, but can't you just use array_key_exists to see if it's already in the array? – CargoMeister Sep 08 '15 at 20:27

0 Answers0