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