Re: string

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Mon, Apr 7, 2008 at 9:30 AM,  <admin@xxxxxxxxxxxxxxxxxxx> wrote:
> Do a preg match to find one or preg_match_all to find all the john in the string.

preg_* is overkill if you're just searching for a literal string.  use
it if you're searching for any strings matching a pattern, part of
which you don't know.  If you know the entire string you're looking
for,  strstr() is both more efficient and easier to use.

Now, strpos() is more efficient still, but arguably more annoying to
use because of the "0 but true" issue that necessitates checking for
!== false.

Besides efficiency, the only difference between strstr() and strpos()
is what they return.  strpos() returns the index of the first match,
while strstr() returns the entire string starting from that point;
it's the building of the copy of the string that causes strstr() to be
less efficient.

Both functions have case-insensitive variants stristr and stripos.

In each case, if the substring occurs more than once within the outer
string, the return value is based on the *first* occurrence. strpos()
(but not strstr()) has a variant that uses the *last* one instead:
strrpos() (r=reverse), which also has a case-insensitive version
strripos().  You can easily define a strrstr() though:

function strrstr($where, $what) {
   $pos = strrpos($where, $what);
   return $pos === false ? false : substr($where, $pos);
}

And for good measure, a strristr:

function strristr($where, $what) {
  $pos = strripos($where, $what);
  return $pos === false ? false : substr($where, $pos);
}




>
>  <?php
>  $name = "John Taylor";
>  $pattern = '/^John/';
>  preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
>  print_r($matches);
>  ?>
>
>
>
>
>
>
>
>  $name = "John Taylor";
>  I want to verify if $name contains "john", if yes echo "found";
>  Cannot remember which to use:
>  http://ca.php.net/manual/en/ref.strings.php
>  Sorry,
>  John
>
>  --
>  PHP General Mailing List (http://www.php.net/)
>  To unsubscribe, visit: http://www.php.net/unsub.php
>
>  --
>  PHP General Mailing List (http://www.php.net/)
>  To unsubscribe, visit: http://www.php.net/unsub.php
>
>



-- 
Mark J. Reed <markjreed@xxxxxxxx>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux