Saturday, December 23, 2006

Strpbrk in Php

In Php 5 the string function strpbrk was introduced (quoting from the manual):

string strpbrk ( string haystack, string char_list )

strpbrk() searches the haystack string for a char_list, and returns a string starting from the character found (or FALSE if it is not found).

This is quite useful in many cases, but unfortunately it's not available in Php 4. However, it should be quite straightforward to implement it. Here's how I did:

function my_strpbrk($haystack, $char_list) {
$pos = strcspn($haystack, $char_list);

if ($pos == strlen($haystack))
return FALSE;

return substr($haystack, $pos);

And this is its usage:



$text = 'This is a Simple text.';

// this echoes "is is a Simple text." because 'i' is matched first
echo my_strpbrk($text, 'mi');

// this echoes "Simple text." because chars are case sensitive
echo my_strpbrk($text, 'S');

// returns FALSE
print (!my_strpbrk($text, 'W') ? "FALSE" : "TRUE");

Just my two little cents :-)

1 comment:

Anonymous said...

hey thanks for that! was doing some work on some creaky server which didn't have PHP5 onboard, but this did the trick just fine.