note 105598 added to function.preg-match
| From: | cmallabon at homesfactory dot com | Date: | Wed, 31 Aug 2011 05:28:48 +0000 |
| Subject: | note 105598 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182846@lists.php.net to get a copy of this message | ||
Just an interesting note. Was just updating code to replace ereg() with strpos() and preg_match and
the thought occured that preg_match() could be optimized to quit early when only searching if a
string begins with something, for example
<?php
if(preg_match("/^http/", $url))
{
//do something
}
?>
vs
<?php
if(strpos($url, "http") === 0)
{
//do something
}
?>
As I guessed, strpos() is always faster (about 2x) for short strings like a URL but for very long
strings of several paragraphs (e.g. a block of XML) when the string doesn't start with the
needle preg_match as twice as fast as strpos() as it doesn't scan the entire string.
So, if you are searching long strings and expect it to normally be true (e.g. validating XML),
strpos() is a much faster BUT if you expect if to often fail, preg_match is the better choice.
----
Server IP: 69.147.83.197
Probable Submitter: 67.168.17.90
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/105598
Del: integrated -- https://master.php.net/note/delete/105598/integrated
Del: useless -- https://master.php.net/note/delete/105598/useless
Del: bad code -- https://master.php.net/note/delete/105598/bad+code
Del: spam -- https://master.php.net/note/delete/105598/spam
Del: non-english -- https://master.php.net/note/delete/105598/non-english
Del: in docs -- https://master.php.net/note/delete/105598/in+docs
Del: other reasons-- https://master.php.net/note/delete/105598
Reject -- https://master.php.net/note/reject/105598
Search -- https://master.php.net/manage/user-notes.php