1

I'm trying to get the index value of an array if there is an "http" initial value, cause the text in the string can be different in others scenario... In this case the array will be:

Array ( [0] => Visit [1] => the [2] => website [3] => https://www.google.it [4] => to [5] => find [6] => other [7] => result )

And i need to find the [3] to build an hyperlink... this is the code that i'm try to use to get it:

$var = "Visit the website https://www.google.it to find other result";

if ( stripos($var, 'http') !== false ) {
    $values = explode(" ", $var);
    $key = array_search('http', $values); //<-- this not work, cause search the exact value
}

One time i have the index, i can build the anchor tag for hyperlink:

<a href="<?= $values[X] ?>">$values[X]</a>

I believe was easy to do, but around the web i haven't found a solution or help... Hope in your help, thanks a lot.

Devilix
  • 334
  • 3
  • 13

1 Answers1

0

I recommend using the PHP filter function as this checks if the string is a valid URL:

$var = "Visit the website https://www.google.it to find other result";

$values = explode(" ", $var); // explode first

$keys_with_url = [];

foreach($values as $key => $value) { // check every element of the array if it's a valid URL
    $validator = filter_var($value, FILTER_VALIDATE_URL); 
    if($validator) {
        $keys_with_url[] = $key; // your URL index
    }
}

or even more compact using array_filter which can also find multiple occurences:

$var = "Visit the website https://www.google.it or https://www.google.de to find other result";

function is_url($value) {
    return filter_var($value, FILTER_VALIDATE_URL);
}

print_r(array_filter($values, "is_url"));

PHP Documentation for filter_var, array_filter and possible filters

Johannes
  • 1,478
  • 1
  • 12
  • 28