Forum Moderators: coopster
// Test 1
$test = false;
$url = 'https://www.example.com/foo/this-is-a-test/12345';
$start_time = microtime(TRUE);
for ($i = 0; $i < 10000; $i++) {
if (strpos($url, 'http') !== false)
$test = 1;
}
$end_time = microtime(TRUE);
echo 'strpos(): ';
echo "#$test#\n";
echo $end_time - $start_time;
echo "\n\n";
// Test 2
$test = false;
$start_time = microtime(TRUE);
for ($i = 0; $i < 10000; $i++) {
if (substr($url, 0, 4) === 'http')
$test = 1;
}
$end_time = microtime(TRUE);
echo 'substr(): ';
echo "#$test#\n";
echo $end_time - $start_time;
If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.
[php.net...]
if (strpos($url, 'http') !== false)
if (substr($url, 0, 4) === 'http')
// Is "http" at the start of $url?
if (strpos($url, 'http') === 0)
- "strpos" stops as soon as it finds the string, it does not necessarily browse the whole string.
In my case I'm just testing to see if the string at least looks like a link before attempting to use cURL
filter_var($url, FILTER_VALIDATE_URL) if (strpos($url, 'http') === 0) {
// using filter_var() to sanitize before processing
$ch = curl_init(filter_var($url, FILTER_VALIDATE_URL));
...
}