How do you pull first 100 characters of a string in PHP - php

I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.
Is there a function that can do this easily?
For example:
$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
$string2 = 100charfunction($string1);
print $string2
To get:
I am looking for a way to pull the first 100 characters from a string vari

$small = substr($big, 0, 100);
For String Manipulation here is a page with a lot of function that might help you in your future work.

You could use substr, I guess:
$string2 = substr($string1, 0, 100);
or mb_substr for multi-byte strings:
$string2 = mb_substr($string1, 0, 100);
You could create a function wich uses this function and appends for instance '...' to indicate that it was shortened. (I guess there's allready a hundred similar replies when this is posted...)

A late but useful answer,
PHP has a function specifically for this purpose.
mb_strimwidth
$string = mb_strimwidth($string, 0, 100);
$string = mb_strimwidth($string, 0, 97, '...'); //optional characters for end

$x = '1234567';
echo substr ($x, 0, 3); // outputs 123
echo substr ($x, 1, 1); // outputs 2
echo substr ($x, -2); // outputs 67
echo substr ($x, 1); // outputs 234567
echo substr ($x, -2, 1); // outputs 6

try this function
function summary($str, $limit=100, $strip = false) {
$str = ($strip == true)?strip_tags($str):$str;
if (strlen ($str) > $limit) {
$str = substr ($str, 0, $limit - 3);
return (substr ($str, 0, strrpos ($str, ' ')).'...');
}
return trim($str);
}

Without php internal functions:
function charFunction($myStr, $limit=100) {
$result = "";
for ($i=0; $i<$limit; $i++) {
$result .= $myStr[$i];
}
return $result;
}
$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
echo charFunction($string1);

Related

how i can display only 2 phrase from sql [duplicate]

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
will do the job.
Take a look here.
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
function trimtext($text, $start, $len)
{
return substr($text, $start, $len);
}
You can call the function like this:
$string = trimtext("this is a string", 0, 10);
Would return:
This is a
substr let's you take a portion of string consisting of exactly as much characters as you need.
You can use this
substr()
function to get substring
If you want to get a string with a certain number of characters you can use substr, i.e.
$newtext = substr($string,0,$length);
where $length is the given length of the new string.
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags)
use this code:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
My function has some length to it, but I like to use it. I convert the string int to a Array.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
Or if the text is coming from an editor and you want to strip out the HTML tags.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
With elipsis (...) only if longer - and taking care of special language-specific characters:
mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;

Replace first character with last character of multiple strings PHP

I have this code
<?php
$str1 = 'Good'
$str2 = 'Weather'
echo $str1, $str2
I need the output as Doog Reathew
Using the below piece of code solves your purpose. Comments have been added for your understanding.
<?php
$str1 = 'Good';
$str2 = 'Weather';
function swaprev($str1)
{
$str1 = str_split($str1); //<--- Split the string into separate chars
$lc=$str1[count($str1)-1]; # Grabbing last element
$fe=$str1[0]; # Grabbing first element
$str1[0]=$lc;$str1[count($str1)-1]=$fe; # Do the interchanging
return $str1 = implode('',$str1); # Recreate the string
}
echo ucfirst((strtolower(swaprev($str1))))." ".ucfirst((strtolower(swaprev($str2))));
OUTPUT :
Doog Reathew
just write below function ,it will work
function replace($string) {
$a = substr($string, 0, 1);
$b = substr($string, -1);
$string = $b . (substr($string, 1, strlen($string)));
$string = substr($string, 0, strlen($string) - 1);
$string = $string . $a;
return ucfirst(strtolower($string));
}

Shuffle new characters after each character in a string

I have the following function to generate a new random character at the beginning and at the end of a string:
function random($string) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$shuffle_start = substr(str_shuffle($chars), 0, 6);
$shuffle_end = substr(str_shuffle($chars), 0, 6);
$str = chunk_split($string, 1, substr(str_shuffle($chars), 0, 5));
return $shuffle_start . $str . $shuffle_end;
}
As you can see for $str I'm trying to get 5 random characters after each letter in the string and it's that I need some help with. As it is now, this function prints this:
dYj9quhDk2T4eDk2T4lDk2T4lDk2T4oDk2T4KHjN6T
The string is "hello" and are covered by 6 random characters at the beginning and at the end of the string (dYj9qu and KHjN6T). After each character inside of this string, you can see Dk2T4 and it's repeatably coming back after each character. This is not how I want it! I want Dk2T4 to be random so the string would look like this:
dYj9quhDk2T4eTft3bl7yjF4lac34vodkiY0KHjN6T
I want also the last characters of the string ("hello" - in this case dkiY0 in the last string) where removed from the string, so it looks like this:
dYj9quhDk2T4eTft3bl7yjF4lac34voKHjN6T
How can I fix this issue?
This happens because the chunk_split evaluates the substr(str_shuffle($chars), 0, 5) only once. You need to iterate the letters and generate the sequence for each one:
function random($string) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$shuffle_start = substr(str_shuffle($chars), 0, 6);
$shuffle_end = substr(str_shuffle($chars), 0, 6);
$letters = str_split($string);
$str = '';
$count = count($letters);
foreach($letters as $l){
$count--;
$str .= $l;
if($count){ // add 5 characters if not last letter
$str .= substr(str_shuffle($chars), 0, 5);
}
}
return $shuffle_start . $str . $shuffle_end;
}

php substring Issue

I have the following string:
$str = "ABACADAF";
I am using the following code:
$first2 = substr($str, 0, 2);
I want to get the following output:
output => `AB,AC,AD,AF`
(Every two characters separated by comma)
But the result I'm getting is not correct.
I checked the php manual but that is not helping, is there some foreach loop to iterate through all the string characters?
Not tested, but should be something along these lines:
<?php
$string = "ABACADAF";
$split = str_split($string, 2);
$implode = implode(",", $split);
echo $implode;
?>
You are looking for str_split function. You can do like this:
$sResult = join(',', str_split($sData, 2));
Alternatively, you can do it via regex:
$sResult = preg_replace('/(..)(?!$)/', '$1,', $sData);
Here's a function that you can use to output from a foreach. We're finding two capital letter matches and putting them into an array, then we implode that array() to make a string.
<?php
function splitter($string){
preg_match_all('/[A-Z]{2}/', $string, $matches);
$newstring = implode(',',$matches[0]);
return $newstring;
}
$strings = array("ABACADAF","ACABAFAC","AAABAFAD","ACACADAF");
foreach($strings as $string){
echo splitter($string)."\n";
}
?>
Output
AB,AC,AD,AF
AC,AB,AF,AC
AA,AB,AF,AD
AC,AC,AD,AF
If you're running a lot of them (millions of lines) you can use this function instead. It's much quicker.
function splitter($string){
$newstring = substr(chunk_split($string, 2, ','), 0, -1);
return $newstring;
}
You could do it like this or recursively as well.
<?php
for ($i=0; $i< strlen($str); $i=$i+3)
{
$str = substr($str,i,2).",".substr($str,3);
}
echo $str;
?>
I personally prefer the recursive implementation:
<?php
function add_comma($str)
{
return substr($str, 0, 2,).','.add_comma(subtr($str,3));
}
echo add_comma($str);
?>
While this is doable with a for loop, it is cleaner (and maybe faster), and more strait-forward in TomUnite's answer.
But since you asked...
With a for loop you could do it like this:
$withCommas = substr($string, 0, 2);
for($i=0; $i < strlen($string); $i += 2){
$withCommas+= "," . substr($string, $i, $i+2);
}
Here is the solution and Same output of your problem:
I personally tested it :
<?php
$str = "ABACADAF";
$first = substr($str, 0, 2);
$second = substr($str, 2, 2);
$third = substr($str, 4, 2);
$fourth = substr($str, 6, 2);
echo $output = $first.",".$second.",".$third.",".$fourth;
?>

Shorten a text string in PHP

Is there a way to trim a text string in PHP so it has a certain number of characters? For instance, if I had the string:
$string = "this is a string";
How could I trim it to say:
$newstring = "this is";
This is what I have so far, using chunk_split(), but it isn't working. Can anyone improve on my method?
function trimtext($text)
{
$newtext = chunk_split($text,15);
return $newtext;
}
I also looked at this question, but I don't really understand it.
if (strlen($yourString) > 15) // if you want...
{
$maxLength = 14;
$yourString = substr($yourString, 0, $maxLength);
}
will do the job.
Take a look here.
substr cuts words in half. Also if word contains UTF8 characters, it misbehaves. So it would be better to use mb_substr:
$string = mb_substr('word word word word', 0, 10, 'utf8').'...';
You didn't say the reason for this but think about what you want to achieve. Here is a function for shorten a string word by word with or without adding ellipses at the end:
function limitStrlen($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
if($last_space !== false) {
$trimmed_text = substr($input, 0, $last_space);
} else {
$trimmed_text = substr($input, 0, $length);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
function trimtext($text, $start, $len)
{
return substr($text, $start, $len);
}
You can call the function like this:
$string = trimtext("this is a string", 0, 10);
Would return:
This is a
substr let's you take a portion of string consisting of exactly as much characters as you need.
You can use this
substr()
function to get substring
If you want to get a string with a certain number of characters you can use substr, i.e.
$newtext = substr($string,0,$length);
where $length is the given length of the new string.
If you want an abstract for the first 10 words (you can use html in $text, before script there is strip_tags)
use this code:
preg_match('/^([^.!?\s]*[\.!?\s]+){0,10}/', strip_tags($text), $abstract);
echo $abstract[0];
My function has some length to it, but I like to use it. I convert the string int to a Array.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
//Turning String into an Array
$split_text = explode(" ", $text);
//Loop for the length of words you want
while($count < $limit - 1){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
Or if the text is coming from an editor and you want to strip out the HTML tags.
function truncate($text, $limit){
//Set Up
$array = [];
$count = -1;
$text = filter_var($text, FILTER_SANITIZE_STRING);
//Turning String into an Array
$split_text = preg_split('/\s+/', $text);
//Loop for the length of words you want
while($count < $limit){
$count++;
$array[] = $split_text[$count];
}
//Converting Array back into a String
$text = implode(" ", $array);
return $text." ...";
}
With elipsis (...) only if longer - and taking care of special language-specific characters:
mb_strlen($text,'UTF-8') > 60 ? mb_substr($text, 0, 60,'UTF-8') . "…" : $text;

Categories