使用PHP查找并替换字符串中子字符串的最后一个实例

时间:2018-02-22 16:26:38

标签: php

我有一份动态的动态列表。每项运动都以,结束。使用,删除了最后一个$sports = substr($sports, 0, -2);。现在,我试图找出如何用,(逗号和空格)替换最后, and(逗号空格)。我可能错过了,但我没有看到这个功能。是否有一种或另一种创造性的方式来实现它?

原始列表

Football, Soccer, Basketball, Swimming, Baseball, Golf, 

所需列表

Football, Soccer, Basketball, Swimming, Baseball, and Golf 

5 个答案:

答案 0 :(得分:3)

$str = substr("Football, Soccer, Basketball, Swimming, Baseball, Golf, ", 0, -2);

$last_comma_position = strrpos($str, ',');

if($last_comma_position != false)
{
    echo substr_replace($str, ' and', $last_comma_position, 1);
}

http://php.net/substr_replace

或作为一项功能

function replace_last($haystack, $needle, $replaceWith)
{
    $last_position = strrpos($haystack, $needle);

    if($last_position != false)
    {
        return substr_replace($haystack, $replaceWith, $last_position, strlen($needle));
    }
}

$str = substr("Football, Soccer, Basketball, Swimming, Baseball, Golf, ", 0, -2);

echo replace_last($str, ',', ' and');

两者都打印出来

Football, Soccer, Basketball, Swimming, Baseball and Golf

答案 1 :(得分:1)

您可以利用explode() / implode()来执行此操作。查看live example here

$list = 'Football, Soccer, Basketball, Swimming, Baseball, Golf, ';

function display( $string ) {
  // Splitting the list by comma
  $str = explode(',', $string);

  // Removing empty items
  $str = array_filter($str, function($item) {
    return strlen(trim($item)) > 0;
  });

  // prepeding "and" before the last item only if it contains more than one item
  $size = count($str);

  if( $size > 1 ) {
    $str[$size - 1] = "and " . (string) $str[$size - 1];
  }

  // Make list great (string) again
  $str = implode(', ', $str);  

  return $str;
}


echo display($list);

将回应:

  

足球,足球,篮球,游泳,棒球和高尔夫

答案 2 :(得分:0)

您可以尝试自己的方法。有点像这样:

$string = "Football, Soccer, Basketball, Swimming, Baseball, Golf,"; 

function addAndToList($string) {

$string = substr($string, 0, -1);
$stringArray = explode(',', $string); 

$resultString = ''; 
foreach ($stringArray as $index => $val) {
  if (!isset($stringArray[$index+1])) 
       $resultString .= 'and '.$val; 
  else 
      $resultString .= $val.', ';
}

return $resultString; 
}

echo addAndToList($string); 

答案 3 :(得分:0)

说明:

  • 匹配字符串的最后一个字
  • 由空格字符分隔
  • 将其存储到后引用伪变量$1
  • 添加所需的字符串
#!/usr/bin/env php
<?php

$sports = "Football, Soccer, Basketball, Swimming, Baseball, Golf, ";
$sports = substr($sports, 0, -2);

echo preg_replace('/ ([a-zA-Z]+)$/', ' and $1', $sports) . "\n";

此片段输出:

Football, Soccer, Basketball, Swimming, Baseball, and Golf

可以在此demo中验证解决方案。

答案 4 :(得分:0)

如果您的变量已经定义,请尝试此操作:

$arr = array_reverse(explode(', ', $sports));
$last = array_shift($arr);
$arr[0] .= " and {$last}";
$sports = implode(', ', array_reverse($arr));
echo "$sports\n";