Do you need a PHP programmer?
Use my services as a freelance PHP programmer by hiring me to do PHP programming on your website project.

I have built many custom PHP applications like project managers, classified ad websites and content management systems. I also work with open source applications such as WordPress, online shopping cart websites like Magento and develop content management systems like Joomla.

Thursday, April 12, 2012

Cut a string after X characters -- PHP

Hi guys, ,
In this my post, let's we talk about string manipulation using PHP code.
There are many functions of php that you can use to manipulation your string.
But now I will share you a simple way how to cut a string after x characters.
We will use 2 manipulation functions of php, they are strlen ( for count characters of your string ) and substr ( for cut characters of your string ).

This is my code :

<?php  
    if(isset($_POST['submit'])){          
            
            $text = $_POST['text'];
            
            //check if you have value in text.  
            if(empty($text)){  
               echo "<h3>Error: Please complete the form.<a href=\"$_SERVER[PHP_SELF]\">back</a></h3>";  
               exit(); //exit the script and don't process the rest of it!  
            }  
            
            $limit = 10; //limit the char will cut
            if (strlen($text) > $limit) {
                $text = substr($text, 0, $limit) . '...'; //if $text more than $limit char will replace with (...)
            } else {
                $text = $text;
            }
                   
            //success message, redirect to main page.          
            $msg = urlencode("Result of your string : <h4>$text</h4> <a href=\"cut_string.php\">Try again?</a>");  
                header("Location: cut_string.php?msg=$msg");  
                exit();  
              
          
    }else{  
            //if there is a message, display it  
            if(isset($_GET['msg']))  
            {  
                //but decode it first!  
    
                echo "<p>".urldecode($_GET['msg'])."</p>";  
            }  
            //the upload form  
        echo "  
        <h1>Simple code to cut a string after X characters PHP - <a href=\"http://bywebs.blogspot.com\">bywebs.blogspot.com</a></h1>
        <form action=\"$_SERVER[PHP_SELF]\" method=\"post\"enctype=\"multipart/form-data\">\n  
        <p>Your text:<input type=\"text\" name=\"text\" /></p>\n  
        <p><input type=\"submit\" name=\"submit\" value=\"Submit\" /></p>";  
    }  
?>

Just a simple code :)
Let's try for your self, for the complete file you can "Download Here".
Hope it useful for all, if you have any question, you can write your comment below :)

Good Luck :)

No comments:

Post a Comment