Replace first character with last character of multiple strings PHP - 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));
}

Related

How to limit word count instead of character count on product short description in woocommerce? [duplicate]

How can I truncate a string after 20 words in PHP?
function limit_text($text, $limit) {
if (str_word_count($text, 0) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
echo limit_text('Hello here is a long sentence that will be truncated by the', 5);
Outputs:
Hello here is a long ...
Change the number 3 to the number 20 below to get the first 20 words, or pass it as parameter. The following demonstrates how to get the first 3 words: (so change the 3 to 20 to change the default value):
function first3words($s, $limit=3) {
return preg_replace('/((\w+\W*){'.($limit-1).'}(\w+))(.*)/', '${1}', $s);
}
var_dump(first3words("hello yes, world wah ha ha")); # => "hello yes, world"
var_dump(first3words("hello yes,world wah ha ha")); # => "hello yes,world"
var_dump(first3words("hello yes world wah ha ha")); # => "hello yes world"
var_dump(first3words("hello yes world")); # => "hello yes world"
var_dump(first3words("hello yes world.")); # => "hello yes world"
var_dump(first3words("hello yes")); # => "hello yes"
var_dump(first3words("hello")); # => "hello"
var_dump(first3words("a")); # => "a"
var_dump(first3words("")); # => ""
To Nearest Space
Truncates to nearest preceding space of target character. Demo
$str The string to be truncated
$chars The amount of characters to be stripped, can be overridden by $to_space
$to_space boolean for whether or not to truncate from space near $chars limit
Function
function truncateString($str, $chars, $to_space, $replacement="...") {
if($chars > strlen($str)) return $str;
$str = substr($str, 0, $chars);
$space_pos = strrpos($str, " ");
if($to_space && $space_pos >= 0)
$str = substr($str, 0, strrpos($str, " "));
return($str . $replacement);
}
Sample
<?php
$str = "this is a string that is just some text for you to test with";
print(truncateString($str, 20, false) . "\n");
print(truncateString($str, 22, false) . "\n");
print(truncateString($str, 24, true) . "\n");
print(truncateString($str, 26, true, " :)") . "\n");
print(truncateString($str, 28, true, "--") . "\n");
?>
Output
this is a string tha...
this is a string that ...
this is a string that...
this is a string that is :)
this is a string that is--
use explode() .
Example from the docs.
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
note that explode has a limit function. So you could do something like
$message = implode(" ", explode(" ", $long_message, 20));
Try regex.
You need something that would match 20 words (or 20 word boundaries).
So (my regex is terrible so correct me if this isn't accurate):
/(\w+\b){20}/
And here are some examples of regex in php.
Simple and fully equiped truncate() method:
function truncate($string, $width, $etc = ' ..')
{
$wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2);
return $wrapped[0] . (isset($wrapped[1]) ? $etc : '');
}
Its not my own creation, its a modification of previous posts. credits goes to karim79.
function limit_text($text, $limit) {
$strings = $text;
if (strlen($text) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
if(sizeof($pos) >$limit)
{
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
return $text;
}
If you code on Laravel just use Illuminate\Support\Str
here is example
Str::words($category->publication->title, env('WORDS_COUNT_HOME'), '...')
Hope this was helpful.
Split the string (into an array) by <space>, and then take the first 20 elements of that array.
With triple dots:
function limitWords($text, $limit) {
$word_arr = explode(" ", $text);
if (count($word_arr) > $limit) {
$words = implode(" ", array_slice($word_arr , 0, $limit) ) . ' ...';
return $words;
}
return $text;
}
Try below code,
$text = implode(' ', array_slice(explode(' ', $text), 0, 32))
echo $text;
Something like this could probably do the trick:
<?php
$words = implode(' ', array_slice(split($input, ' ', 21), 0, 20));
use PHP tokenizer function strtok() in a loop.
$token = strtok($string, " "); // we assume that words are separated by sapce or tab
$i = 0;
$first20Words = '';
while ($token !== false && $i < 20) {
$first20Words .= $token;
$token = strtok(" ");
$i++;
}
echo $first20Words;
based on 動靜能量's answer:
function truncate_words($string,$words=20) {
return preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
}
or
function truncate_words_with_ellipsis($string,$words=20,$ellipsis=' ...') {
$new = preg_replace('/((\w+\W*){'.($words-1).'}(\w+))(.*)/', '${1}', $string);
if($new != $string){
return $new.$ellipsis;
}else{
return $string;
}
}
This worked me for UNICODE (UTF8) sentences too:
function myUTF8truncate($string, $width){
if (mb_str_word_count($string) > $width) {
$string= preg_replace('/((\w+\W*|| [\p{L}]+\W*){'.($width-1).'}(\w+))(.*)/', '${1}', $string);
}
return $string;
}
Here is what I have implemented.
function summaryMode($text, $limit, $link) {
if (str_word_count($text, 0) > $limit) {
$numwords = str_word_count($text, 2);
$pos = array_keys($numwords);
$text = substr($text, 0, $pos[$limit]).'... Read More';
}
return $text;
}
As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.
I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.
Here's one I use:
$truncate = function( $str, $length ) {
if( strlen( $str ) > $length && false !== strpos( $str, ' ' ) ) {
$str = preg_split( '/ [^ ]*$/', substr( $str, 0, $length ));
return htmlspecialchars($str[0]) . '…';
} else {
return htmlspecialchars($str);
}
};
return $truncate( $myStr, 50 );
Another solution :)
$aContent = explode(' ', $cContent);
$cContent = '';
$nCount = count($aContent);
for($nI = 0; ($nI < 20 && $nI < $nCount); $nI++) {
$cContent .= $aContent[$nI] . ' ';
}
trim($cContent, ' ');
echo '<p>' . $cContent . '</p>';
To limit words, am using the following little code :
$string = "hello world ! I love chocolate.";
$explode = array_slice(explode(' ', $string), 0, 4);
$implode = implode(" ",$explode);
echo $implode;
$implot will give : hello world ! I
function getShortString($string,$wordCount,$etc = true)
{
$expString = explode(' ',$string);
$wordsInString = count($expString);
if($wordsInString >= $wordCount )
{
$shortText = '';
for($i=0; $i < $wordCount-1; $i++)
{
$shortText .= $expString[$i].' ';
}
return $etc ? $shortText.='...' : $shortText;
}
else return $string;
}
Simpler than all previously posted regex techniques, just match the first n sequences of non-word followed by sequences of word characters. Making the non-word characters optional allows matching of word characters from the start of the string. Greedy word character matching ensures that consecutive word characters are never treated as individual words.
By writing \K in the pattern after matching n substrings, then matching the rest of the string (add the s pattern modifier if you need dots to match newlines), the replacement can be an empty string.
Code: (Demo)
function firstNWords(string $string, int $limit = 3) {
return preg_replace("/(?:\W*\w+){{$limit}}\K.*/", '', $string);
}
Lets assume we have the string variables $string, $start, and $limit we can borrow 3 or 4 functions from PHP to achieve this. They are:
script_tags() PHP function to remove the unnecessary HTML and PHP
tags (if there are any). This wont be necessary, if there are no HTML or PHP tags.
explode() to split the $string into an array
array_splice() to specify the number of words and where it'll start
from. It'll be controlled by vallues assigned to our $start and $limit variables.
and finally, implode() to join the array elements into your truncated
string..
function truncateString($string, $start, $limit){
$stripped_string =strip_tags($string); // if there are HTML or PHP tags
$string_array =explode(' ',$stripped_string);
$truncated_array = array_splice($string_array,$start,$limit);
$truncated_string=implode(' ',$truncated_array);
return $truncated_string;
}
It's that simple..
I hope this was helpful.
I made my function:
function summery($text, $limit) {
$words=preg_split('/\s+/', $text);
$count=count(preg_split('/\s+/', $text));
if ($count > $limit) {
$text=NULL;
for($i=0;$i<$limit;$i++)
$text.=$words[$i].' ';
$text.='...';
}
return $text;
}
function limitText($string,$limit){
if(strlen($string) > $limit){
$string = substr($string, 0,$limit) . "...";
}
return $string;
}
this will return 20 words. I hope it will help
$text='some text';
$len=strlen($text);
$limit=500;
// char
if($len>$limit){
$text=substr($text,0,$limit);
$words=explode(" ", $text);
$wcount=count($words);
$ll=strlen($words[$wcount]);
$text=substr($text,0,($limit-$ll+1)).'...';
}
function wordLimit($str, $limit) {
$arr = explode(' ', $str);
if(count($arr) <= $limit){
return $str;
}
$result = '';
for($i = 0; $i < $limit; $i++){
$result .= $arr[$i].' ';
}
return trim($result);
}
echo wordLimit('Hello Word', 1); // Hello
echo wordLimit('Hello Word', 2); // Hello Word
echo wordLimit('Hello Word', 3); // Hello Word
echo wordLimit('Hello Word', 0); // ''
I would go with explode() , array_pop() and implode(), eg.:
$long_message = "I like summer, also I like winter and cats, btw dogs too!";
$trimmed_message = explode(" ", $long_message, 5); // <-- '5' means 4 words to be returned
array_pop($trimmed_message); //removing last element from exploded array
$trimmed_message = implode(" ", $trimmed_message) . '...';
Result:
I like summer, also...
what about
chunk_split($str,20);
Entry in the PHP Manual
function limit_word($start,$limit,$text){
$limit=$limit-1;
$stripped_string =strip_tags($text);
$string_array =explode(' ',$stripped_string);
if(count($string_array)>$limit){
$truncated_array = array_splice($string_array,$start,$limit);
$text=implode(' ',$truncated_array).'...';
return($text);
}
else{return($text);}
}

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;

Separation of string into multiple string value

I have a string with underscores(_). What I want is to get the string value after the first underscore and considered as the first string value and the second string value will be the whole string after the underscore of the first string value using php.
Example:
$string = "Makes_me_wonder";
Result I want:
$str1 = "me";
$str2 = "wonder";
Another variable I am having:
$string = "I_wont_gohome_withoutyou";
Result should be:
$str1 = "wont";
$str2 = "gohome_withoutyou";
Another one:
$string = 'Never_gonna_leave_this_bed";
Output i want:-
$str1 = "gonna_leave";
$str2 = "this_bed";
Please help me. Thanks.
You can use explode with 3rd parameter - limit:
DEMO
$string = "I_wont_gohome_withoutyou";
$arr = explode("_",$string,3);
$str1 = $arr[1]; //wont
$str2 = $arr[2]; //gohome_withoutyou
Provided that you have two or more _ in a word strictly. If it is so, there needs a work around too.
function explode($string)
{
$delimiter = '_';
return explode($delimiter, explode($delimiter, $string, 2)[1], 2);
}
$string = "Makes_me_wonder";
$strings = explode($string);
echo $strings[0]; //me
echo $strings[1]; //wonder
$string = "I_wont_gohome_withoutyou";
$strings = explode($string);
echo $strings[0]; //wont
echo $strings[1]; //gohome_withoutyou
I think your solution is like this:-
<?php
function getfinal_result($string){
$final_data = explode('_',$string,2)[1]; // explode with first occurrence of _ and leave first word
if(substr_count($final_data,'_')>2){ // now check _ remains is greater that 2
$first_data = substr($final_data , 0, strpos($final_data , '_', strpos($final_data , '_')+1)); // find the string comes after second _
$second_data = str_replace($first_data.'_','',$final_data); // get the string before the second _
$last_data = Array($first_data,$second_data); // assign them to final data
}else{
$last_data = explode('_',$final_data,2); // directly explode with first occurance of _
}
return $last_data; // return final data
}
$first_data = getfinal_result('Makes_me_wonder');
$second_data = getfinal_result('I_wont_gohome_withoutyou');
$third_data = getfinal_result('Never_gonna_leave_this_bed');
echo "<pre/>";print_r($first_data);
echo "<pre/>";print_r($second_data);
echo "<pre/>";print_r($third_data);
?>
Output:- https://eval.in/593240
There are multiple methods but here's one of them.
$pos1 = strpos($string, '_');
$pos2 = strpos($string, '_', $pos1 + 1);
$str1 = substr($string, $pos1 + 1, $pos2 - $pos1 - 1);
$str2 = substr($string, $pos2 + 1);
This assumes that there are at least 2 underscores in the string.

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