10 PHP code snippets for working with strings

by Jean. 38 Comments -

Strings are a very important kind of data, and you have to deal with them daily with web development tasks. In this article, I have compiled 10 extremely useful functions and code snippets to make your php developer life easier.

Automatically remove html tags from a string

On user-submitted forms, you may want to remove all unnecessary html tags. Doing so is easy using the strip_tags() function:

$text = strip_tags($input, "");

Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Get the text between $start and $end

This is the kind of function every web developer should have in their toolbox for future use: give it a string, a start, and an end, and it will return the text contained with $start and $end.

function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    return '';

Source: http://www.jonasjohn.de/snippets/php/get-between.htm

Transform URL to hyperlinks

If you leave a URL in the comment form of a WordPress blog, it will be automatically transformed into a hyperlink. If you want to implement the same functionality in your own website or web app, you can use the following code:

$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);

Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Split text up into 140 char array for Twitter

As you probably know, Twitter only accepts messages of 140 characters or less. If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.

function split_to_chunks($to,$text){
	$total_length = (140 - strlen($to));
	$text_arr = explode(" ",$text);
	foreach ($text_arr as $word){
		if ( strlen($message[$i] . $word . ' ') <= $total_length ){
			if ($text_arr[count($text_arr)-1] == $word){
				$message[$i] .= $word;
			} else {
				$message[$i] .= $word . ' ';
		} else {
			if ($text_arr[count($text_arr)-1] == $word){
				$message[$i] = $word;
			} else {
				$message[$i] = $word . ' ';
	return $message;

Source: http://www.phpsnippets.info/split-text-up-into-140-char-array-for-twitter

Remove URLs from string

When I see the amount of URLs people try to leave in my blog comments to get traffic and/or backlinks, I think I should definitely give a go to this snippet!

$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);

Source: http://snipplr.com/view.php?codeview&id=15236

Convert strings to slugs

Need to generate slugs (permalinks) that are SEO friendly? The following function takes a string as a parameter and will return a SEO friendly slug. Simple and efficient!

function slug($str){
	$str = strtolower(trim($str));
	$str = preg_replace('/[^a-z0-9-]/', '-', $str);
	$str = preg_replace('/-+/', "-", $str);
	return $str;

Source: http://snipplr.com/view.php?codeview&id=2809

Parse CSV files

CSV (Coma separated values) files are an easy way to store data, and parsing them using PHP is dead simple. Don’t believe me? Just use the following snippet and see for yourself.

$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
    echo "Contact: {$line[1]}";

Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1

Search for a string in another string

If a string is contained in another string and you need to search for it, this is a very clever way to do it:

function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    return strpos($content,$str) ? true : false;

Source: http://www.jonasjohn.de/snippets/php/contains.htm

Check if a string starts with a specific pattern

Some languages such as Java have a startWith method/function which allows you to check if a string starts with a specific pattern. Unfortunately, PHP does not have a similar built-in function.
Whatever- we just have to build our own, which is very simple:

function String_Begins_With($needle, $haystack {
    return (substr($haystack, 0, strlen($needle))==$needle);

Source: http://snipplr.com/view.php?codeview&id=2143

Extract emails from a string

Ever wondered how spammers can get your email address? That’s simple, they get web pages (such as forums) and simply parse the html to extract emails. This code takes a string as a parameter, and will print all emails contained within. Please don’t use this code for spam ;)

function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();

$test_string = 'This is a test string...


        Test different formats:
        <a href="test3@example.org">foobar</a>

        strange formats:
        test8@ example.org



Source: http://www.jonasjohn.de/snippets/php/extract-emails.htm

Comments (38) - Leave yours

  1. Alex said:

    The “Search for a string in another string” example could be wrong if the string is at the beginning of the content string which will result of 0 which is false. The correct way of doing it would be:

    return strpos($content,$str) !== false;

  2. Volomike said:

    My replacement for contains is a one-liner without a function:

    if (strpos(‘ ‘ . $sHaystack, $sNeedle)>0) { …then

    For checking inverse of that, as in a NOT condition, do:

    if (strpos(‘ ‘ . $sHaystack, $sNeedle) === FALSE) { …then

    And swap strpos with stripos if you want a case-insensitive search.

  3. Lew A said:

    oh, it’s stripping the tasg (ie. my last comment):

    $url = “Jean-Baptiste Jung (http://www.webdevcat.com)”;
    $url = preg_replace(“#http://([A-z0-9./-]+)#”, ‘<a href=”$1″>$0</a>’, $url);

  4. Nox said:

    ad Search for a string in another string:
    I’m not sure if we can call this “extremely useful function,” besides being trivial also:

    Not just that there is a specific function in standard library, when using $ignorecase in this snippet you will *copy* both variables (PHP uses copy-on-write so normally then wouldn’t be copied even when not using references)

    So in faster and less memory-demanding way:
    $ignorecase ? stripos($content, $str) : strpos($content, $str)
    or if we feel the need of encapsulating into function then:
    function contains($content, $str, $ignorecase = true){
    return $ignorecase ? stripos($content, $str) : strpos($content, $str);

    • nickf said:

      It would have to be:

      return false !== ($ignorecase ? stripos($content, $str) : strpos($content, $str);

  5. Oren Yomtov said:

    There is a better way to implement the “Search for a string in another string”, using the stripos:

  6. OIS said:

    I dont see a huge need for these functions since they are practically built in:

    function String_Begins_With($needle, $haystack) {
    return strpos($haystack, $needle) === 0;

    function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
    return stripos($content, $str) !== false;
    return strpos($content, $str) !== false;

    • OIS said:

      function split_to_chunks($to,$text){
      $length = -1 * (strlen($text) – (140 – strlen($to)));
      $pos = strrpos($text, ‘ ‘, $length);
      return substr($text, 0, $pos);

  7. Charles said:

    Thanks for passing these along. However, two of the entries should be avoided, or improved:

    “Get the text between $start and $end”
    GetBetween() fails a number of simple tests:
    GetBetween( ‘a[b[c]d’, ‘[', ']‘ )
    GetBetween( ‘a]b[c', '[', ']‘ )

    “Convert strings to slugs”
    This one fails, by converting, for instance, “http://www.” into “http-www-”.

  8. Oliver said:

    I think, most of them are useless, as there are better native php functions:

    Get the text between $start and $end => substr()
    Split text up into 140 char array for Twitter => wordwrap/explode
    Remove URLs from string strip_tags
    Parse CSV files => file/explode
    Search for a string in another string => strpos/stripos
    Check if a string starts with a specific pattern => strpos === 0

    And most of these and the other examples are far away from good programming. Sorry stranger.

  9. Luis Salazar said:

    I agree on this: most of them are really useless. But not only that, the worst thing is this kind of things contribute to the whole mess with PHP standardization and good practices. I really really appreciate the time and effort someone takes with good intention to share knowledge! 1000+ points to that!! thats good karma. But, to be honest, that leads to bad programming and shitty software. My advice: read the manual first and practice, practice, practice.

  10. jordan kicks said:

    These strips all HTML tags gives you the option to preserve the ones you define. It also takes into account tags like removing all the javascript, too! You can also strip out all the content between any tag that has an opening and closing tag, like , , etc.soom

  11. droope said:

    Hi :)

    I have a great url matching regex, that could be used for the “replace urls with links section of this post.

    The regex is:

    I’ve found it @ http://daringfireball.net/2009/11/liberal_regex_for_matching_urls

    You can find an explaination for it there. It works great for me :)


  12. vipin said:

    i have just started to learn PHP and about to complete my first book on it. so these code will definitely help me how professionals write code and will also be a kind of exercise for me. Thanks for sharing this.

  13. aTechAdviser said:

    Hey nice article as usually. Just want to say that maybe preg_match or preg_match_all is the better option for:
    Get the text between $start and $end.
    preg_match_all(“/$start(.*?)$end/is”, $input, $out);
    $text_between = trim($out[1][0]);
    echo $text_between; // or return this if use in a function

    Otherwise nice PHP snippets

  14. vansci123 said:

    the worst thing is this kind of things contribute to the whole mess with PHP standardization and good practices.I am not a PHP developper but it is gonna be usefull anyway

  15. Jeff said:

    Could some one explain me what preg_replace does in

    $url = preg_replace(“#http://([A-z0-9./-]+)#”, ‘$0′, $url);

    because I think it does nothing

  16. Krrish said:

    Useful Examples… I Liked the second (Get the text between $start and $end) and last (email) example… Bookmarked this for future reference.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!