Useful Code Snippets / Tutorials – PHP

  • Remove or replace a block of text with definable starting and ending pattern.

    $temp = preg_replace("'<div class="botmenu"[^>]*?>.*?</div>'si", "", $temp);

  • Modify group of links.
    This could be useful, for example, if you have links to multiple articles on a website that then redesigns and thus all its URLs change.

    $temp = preg_replace("/<a href="(.*)html*(.*)">(.*)</a>/i", "<a href="http://www.domain.com/1html2">3</a>", $temp);

  • What’s the easiest way to remove characters from the end of a string?
    See the function substr:
    For example:

    $rest = substr("abcdef", 1, -1); // returns "bcde"

    to remove characters from the end of a string you can use:

    $rest = substr("abcdef", 0, -2); // returns "abcd"

  • How can I get a string of words from a form into an array? Should I use explode or split to separate a string of words?
    If you know that there will only be single spaces between the words then you can use explode:

    $words_array = explode(" ",$words_string);

    If you are getting the string from a form or it might contain extra spaces then you probably should use split or preg_split, which will match regular expressions:

    $words_array = split(" +",$words_string);

  • How can I convert an array into a string?
    Try using the implode function. For example to make a string where all the values of an array are separated by a semicolon:

    $semicolon_separated_string = implode($array, ";");

  • How to change php variables to javascript variables?

    $test = "hello";
    echo "<script> var jstest = '$test'; </script>";

  • How can I build a search engine for my site using PHP?
    Why not have a look at ht://Dig instead? If that doesn’t work for you, check out the PHP search routine I wrote and which can be downloaded on this site, or check out the article, Quick and Dirty Search Engine with PHP and MySQL by Clay Johnson.

  • How can I generate a random alphanumeric password?
    Try using the crypt command, like this:

    $myPass = substr(ereg_replace("[^A-Za-z]", "", crypt(time())) .
      ereg_replace("[^A-Za-z]", "", crypt(time())) .
      ereg_replace("[^A-Za-z]", "", crypt(time())),
      0, 6);

    the three crypts should ensure that you get enough Alpha characters.

  • How do I get the first n words of a string?
    The best way is to create an array from all the words of the string by exploding the string on the space character. You can then use a loop to reassemble a new string from the first n elements in the array. Note that when picking a number (here we want the first 25 words), you need to subtract one(1) from the number, because arrays start on the 0th element and not the 1st.

    $word_array = explode(" ",$longdesc);
    for($x=0; $x<=24; $x++) {
      $shortdesc.=$word_array[$x]." ";
    }
    if (count($word_array)>25) $shortdesc .= "...";
    echo $shortdesc;

    NOTE: This can also be used to get the last n words by modifying the for loop slightly:

    for($x=count($array)-24; $x<=count($array); $x++)

  • Use getimagesize function to see if image actually exists.

    $size = getimagesize($img_url);
    $width = $size[0]; // Index 0
    $height = $size[1]; // Index 1
    if ($width) {
    }

  • Check if a file exists on YOUR server.

    $file = "/path/filename";
    if (file_exists($file)) {
    }

  • Check if a file exists on ANOTHER server.

    $url = "http://www.domain.com/filename";
    if (@$array_of_lines = file($url)) {
    }

  • Why do I get the error "Maximum execution time exceeded"? How can I change the max execution time in PHP?
    PHP scripts are aborted after the maximum execution time has been exceeded. The default is 30 seconds. You can change this setting in your php.ini file with the line that looks like:

    max_execution_time = 30;

    You can also change the timeout via the .htaccess file with the following command:

    php_value max_execution_time 60

    Or, in your PHP script you can use:

    set_time_limit(50);

    I have a complete section on PHP Configuration.

  • How can I get a list of all files in a directory?

  • Easily Create Charts
    JpGraph is an Object-Oriented Graph creating library completely written in PHP and ready to be used in any PHP scripts (CGI/APXS/CLI versions of PHP are supported). The library can be used to create numerous types of graphs either on-line or written to a file. JpGraph makes it easy to draw both "quick and dirty" graphs with a minimum of code as well as complex graphs which requires a very fine grained control. The library assigns context sensitive default values for most of the parameters which minimizes the learning curve. The features are there when you need them – not as an obstacle to overcome!
  • Convert Smart Quotes with PHP
    A question that seems to come up pretty frequently on various PHP mailing lists is how to convert "smart quotes" to real quotes. Chris Shiflett modified an example from Dan Convissor for latin encoding:

    Unfortunately, this won’t help much if you are encoding in UTF-8 (which I recommend). However, in the comments to Chris’s post, someone named Mark came up with a version for UTF-8 encoding.

  • Strip/remove blank or empty lines from text
    For those times when you have some string or block of text that has extra lines you’d like to remove, try this small PHP regex function:

    function removeEmptyLines($string) {
      return preg_replace("!^\s+(\D)!m", "\\1", $string);
    }

Like this content? Why not share it?
Share on FacebookTweet about this on TwitterShare on LinkedInBuffer this pagePin on PinterestShare on Redditshare on TumblrShare on StumbleUpon
There Are No Comments
Click to Add the First »