php格式字符串删除第1个元素

时间:2018-05-29 15:39:48

标签: php arrays json

如何从下面的字符串中删除第一个值,我想删除'键入'只有价值

  

发布类型..:输入

     

发布类型..:文章

     

发布类型..:艺术家&制造商

     

发布类型..:视频

     

发布类型..:在新闻中

     

发布类型..:你知道吗?

     

发布类型..:词汇表A - Z

     

发布类型..:活动

     

发布类型..:最新目录

我尝试将上面的内容转换为数组并尝试删除我尝试过的第一个条目。]或者可以在不将它们转换为数组的情况下完成。

foreach($posttype as $post){
if(getCapitalLetters($post)){
    $array = preg_split("/(\r\n|\n|\r)/", $post);   //converting them to array
    echo '<pre>';echo 'Post type..:';
    echo str_replace(array('\'', '"'), '', substr($post,0,-2));

    }
}



function getCapitalLetters($str)
{
  if(preg_match_all('#([A-Z]+)#',$str,$matches))
  {
    //echo 'Matches';print_r($matches);
    return implode('',$matches[1]);
  }
  else
    return false;
}

1 个答案:

答案 0 :(得分:1)

从你上次的评论来看,我想出了这个:

$posttype = 'Post type..:Type

Post type..:Articles

Post type..:Artists & Makers

Post type..:Videos

Post type..:In The Press

Post type..:Did You Know ?

Post type..:Glossary A - Z

Post type..:Events

Post type..:Recent Catalogs';

$posttypearray = preg_split('/(\r\n|\n|\r)/',$posttype,-1, PREG_SPLIT_NO_EMPTY);

echo "<pre>";
print_r($posttypearray);
echo "</pre>";

$cleanposttypearray = preg_replace('/.*\.\.:(.*)$/','$1',$posttypearray);

echo "<pre>";
print_r($cleanposttypearray);
echo "</pre>";

此代码的输出为:

Array
(
    [0] => Post type..:Type
    [1] => Post type..:Articles
    [2] => Post type..:Artists & Makers
    [3] => Post type..:Videos
    [4] => Post type..:In The Press
    [5] => Post type..:Did You Know ?
    [6] => Post type..:Glossary A - Z
    [7] => Post type..:Events
    [8] => Post type..:Recent Catalogs
)
Array
(
    [0] => Type
    [1] => Articles
    [2] => Artists & Makers
    [3] => Videos
    [4] => In The Press
    [5] => Did You Know ?
    [6] => Glossary A - Z
    [7] => Events
    [8] => Recent Catalogs
)

做什么:

  • 使用preg_split选项 PREG_SPLIT_NO_EMPTY 。这会切割数组中的行并自动刷新空数组值(即$posttype中的空行)。
  • 然后使用preg_replace仅保留..:后面的内容。 preg_replace会为您在数组的每个元素上应用您想要的替换。无需循环。

这就是我将输入转换为每种类型数组的方式。