Over a million developers have joined DZone.

10 PHP code snippets for working with strings

DZone's Guide to

10 PHP code snippets for working with strings

· Web Dev Zone
Free Resource

Should you build your own web experimentation solution? Download this whitepaper by Optimizely to find out.

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, "");


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./-]+)#", '<a href="http://www.catswhocode.com/blog/$1" style="font-size: 12px; vertical-align: baseline; background-color: transparent; margin: 0px; padding: 0px; color: #3777af; text-decoration: none; font-weight: bold">$0</a>', $url);


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]}";


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;


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

Implementing an Experimentation Solution: Choosing whether to build or buy?


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}