array_pop for string in PHP? - php

Pop the last x bytes of a string off the string and return it. Any classic way to do it in PHP other than a custom function like this?
function string_pop(&$str, $num) {
$pop = substr($str, - $num);
$str = substr($str, 0, strlen($str) - $num);
return $pop;
}

Maybe something like
list($str, $pop) = str_split($str, strlen($str) - $num);
EDIT: As pointed out by Gergo Erdosi, this code will only work if the $num is less than half of the length of $str. The following would work otherwise.
$arr = str_split($str, strlen($str) - $num);
$pop = array_pop($arr);
$str = implode('', $arr);
But whether or not this is more elegant than you're original function is debatable.

Not sure it's the most efficient, but here is a one liner:
list($str, $pop) = preg_split('/(?<=.{'.(strlen($str) - $num).'})/', $str, 2);

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;

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;

Remove a string from the beginning of a string

I have a string that looks like this:
$str = "bla_string_bla_bla_bla";
How can I remove the first bla_; but only if it's found at the beginning of the string?
With str_replace(), it removes all bla_'s.
Plain form, without regex:
$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
if (substr($str, 0, strlen($prefix)) == $prefix) {
$str = substr($str, strlen($prefix));
}
Takes: 0.0369 ms (0.000,036,954 seconds)
And with:
$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);
Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.
Profiled on my server, obviously.
You can use regular expressions with the caret symbol (^) which anchors the match to the beginning of the string:
$str = preg_replace('/^bla_/', '', $str);
function remove_prefix($text, $prefix) {
if(0 === strpos($text, $prefix))
$text = substr($text, strlen($prefix)).'';
return $text;
}
Here's an even faster approach:
// strpos is faster than an unnecessary substr() and is built just for that
if (strpos($str, $prefix) === 0) $str = substr($str, strlen($prefix));
Here.
$array = explode("_", $string);
if($array[0] == "bla") array_shift($array);
$string = implode("_", $array);
In PHP 8+ we can simplify using the str_starts_with() function:
$str = "bla_string_bla_bla_bla";
$prefix = "bla_";
if (str_starts_with($str, $prefix)) {
$str = substr($str, strlen($prefix));
}
https://www.php.net/manual/en/function.str-starts-with.php
EDIT: Fixed a typo (closing bracket) in the example code.
Nice speed, but this is hard-coded to depend on the needle ending with _. Is there a general version? – toddmo Jun 29 at 23:26
A general version:
$parts = explode($start, $full, 2);
if ($parts[0] === '') {
$end = $parts[1];
} else {
$fail = true;
}
Some benchmarks:
<?php
$iters = 100000;
$start = "/aaaaaaa/bbbbbbbbbb";
$full = "/aaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee";
$end = '';
$fail = false;
$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
if (strpos($full, $start) === 0) {
$end = substr($full, strlen($start));
} else {
$fail = true;
}
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "strpos+strlen", $t);
$t0 = microtime(true);
for ($i = 0; $i < $iters; $i++) {
$parts = explode($start, $full, 2);
if ($parts[0] === '') {
$end = $parts[1];
} else {
$fail = true;
}
}
$t = microtime(true) - $t0;
printf("%16s : %f s\n", "explode", $t);
On my quite old home PC:
$ php bench.php
Outputs:
strpos+strlen : 0.158388 s
explode : 0.126772 s
Lots of different answers here. All seemingly based on string analysis. Here is my take on this using PHP explode to break up the string into an array of exactly two values and cleanly returning only the second value:
$str = "bla_string_bla_bla_bla";
$str_parts = explode('bla_', $str, 2);
$str_parts = array_filter($str_parts);
$final = array_shift($str_parts);
echo $final;
Output will be:
string_bla_bla_bla
Symfony users can install the string component and use trimPrefix()
u('file-image-0001.png')->trimPrefix('file-'); // 'image-0001.png'
I think substr_replace does what you want, where you can limit your replace to part of your string:
http://nl3.php.net/manual/en/function.substr-replace.php (This will enable you to only look at the beginning of the string.)
You could use the count parameter of str_replace ( http://nl3.php.net/manual/en/function.str-replace.php ), this will allow you to limit the number of replacements, starting from the left, but it will not enforce it to be at the beginning.

How do you pull first 100 characters of a string in 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);

Categories