PHP - 在删除第一个单词时转换带破折号的字符串


PHP - Convert a string with dashes while removing first word

$title = '228-example-of-the-title'

我需要将字符串转换为:

标题示例

我该怎么做?

单行,

$title = '228-example-of-the-title';
ucwords(implode(' ', array_slice(explode('-', $title), 1)));
  • 这会在短划线 ( explode(token, input) ), 上拆分字符串 ),
  • 减去第一个元素 ( array_slice(array, offset)
  • 用空格 ( implode(glue, array) ) 连接生成的集合备份,
  • 最后将每个单词大写(感谢萨拉特)。
$title = '228-example-of-the-title'
$start_pos = strpos($title, '-');
$friendly_title = str_replace('-', ' ', substr($title, $start_pos + 1));

您可以使用以下代码执行此操作

$title = '228-example-of-the-title';
$parts = explode('-',$title);
array_shift($parts);
$title = implode(' ',$parts); 

使用的功能:爆炸内爆和array_shift

$pieces = explode("-", $title);
$result = "";
for ($i = 1; $i < count(pieces); $i++) {
    $result = $result . ucFirst($pieces[$i]);
}
$toArray = explode("-",$title);
$cleanArray = array_shift($toArray);
$finalString = implode(' ' , $cleanArray);
// echo ucwords($finalStirng);

使用 explode() 拆分 "-" 并将字符串放入数组中

$title_array = explode("-",$title);
$new_string = "";
for($i=1; $i<count($title_array); $i++)
{
$new_string .= $title_array[$i]." ";
}
echo $new_string;