Replacing the comma & before the last word in a string

Having few problems with what should ideally be a simple task.

What I'm trying to do is replace the ', ' before the last word & .

So basically, if there is a word in $ddd than what you need, it is like DDD, and if $ddd empty than & CCC

Theoretically, what I need is the following:

"AAA, BBB, CCC and DDD" when all 4 words are not empty "AAA, BBB and CCC" when 3 are not empty and the last is "AAA and BBB" when 2 are not empty and the last 2 words are empty " AAA "when only one returns non-empty.

Here is my script

  $aaa = "AAA"; $bbb = ", BBB"; $ccc = ", CCC"; $ddd = ", DDD"; $line_for = $aaa.$bbb.$ccc.$ddd; $wordarray = explode(', ', $line_for); if (count($wordarray) > 1 ) { $wordarray[count($wordarray)-1] = '& '.($wordarray[count($wordarray)-1]); $line_for = implode(', ', $wordarray); } 

Please do not judge me, as this is just an attempt to create what I tried to describe above.

Please, help

+6
source share
4 answers

I think this is the best way to do this:

 function replace_last($haystack, $needle, $with) { $pos = strrpos($haystack, $needle); if($pos !== FALSE) { $haystack = substr_replace($haystack, $with, $pos, strlen($needle)); } return $haystack; } 

and now you can use it like this:

 $string = "AAA, BBB, CCC, DDD, EEE"; $replaced = replace_last($string, ', ', ' &amp; '); echo $replaced.'<br>'; 
0
source

Here I take this using array_pop() :

 $str = "A, B, C, D, E"; $components = explode(", ", $str); if (count($components) <= 1) { //If there only one word, and no commas or whatever. echo $str; die(); //You don't have to *die* here, just stop the rest of the following from executing. } $last = array_pop($components); //This will remove the last element from the array, then put it in the $last variable. echo implode(", ", $components) . " &amp; " . $last; 
+6
source

Regular Expression Solution:

 $str = "A, B, C, D, E"; echo preg_replace('~,(?=[^,]+$)~', '&amp;', $str); 

Regular expression explanation:

 , -- a comma (?=[^,]+$) -- followed by one or more any characters but `,` and the end of the string 

Claims documentation (positive view (?= ... ) was used in my answer): http://www.php.net/manual/en/regexp.reference.assertions.php

+1
source

Here is another way:

 $str = "A, B, C, D, E"; $pos = strrpos($str, ","); //Calculate the last position of the "," if($pos) $str = substr_replace ( $str , " & " , $pos , 1); //Replace it with "&" // ^ This will check if the word is only of one word. 

For those who like to copy a function, here is one :)

 function replace_last($haystack, $needle, $with) { $pos = strrpos($haystack, $needle); return $pos !== false ? substr_replace($haystack, $with, $pos, strlen($needle)) : $haystack; } 
0
source

Source: https://habr.com/ru/post/950418/


All Articles