php字符串解析基于相同的分隔符

时间:2015-07-05 22:10:16

标签: php string

由于某个网站的格式可怕且不一致,我们正在接收数据,我需要解析以下字符串

$s = array('James Cussen\'s Destructor Bot',
           'Andre Riverra\'s Quick-Runner - San francisco', 
           'Kim Smith\'s - NightBot');

进入:

James Cussen: Destructor Bot
Andre Riverra Quick-Runner
  Kim Smith Nightbot

我的问题是用两个' - '解析一条线的最佳方法是什么?进入相应的所有者:名称格式。

$bot ='';
$creator = '';

foreach($s as $parse)
{

   //if string contains '
    if(strpos($parse,'\'') !== false)
            {

              if(substr_count ($parse, '-') > 1)
              {
                  $arr =  explode('\'', $parse);


                  $line =  trim(substr($arr[1], 1));


              }
               if(strpos($parse,'–') !== false)
                 {
                 $temp = explode('–',$parse);
                 }
                 else
                 {
                 $temp =  explode('-', $parse);
                 }

                $arr =  explode('\'', $temp[0]);
                $creator = $arr[0];

                $bot =  trim(substr($arr[1], 1));


            }

    echo $creator.':'.$bot;
    echo '<br>';
}

1 个答案:

答案 0 :(得分:1)

将来这肯定会失败,因为数据传输的格式不一致,但是,至少它现在可以正常工作。

foreach ($s as $entry):
    list($creator, $bot) = explode('\'s', $entry);
    if (substr($bot, 0, 3) !== ' - '):
        $bot = substr($bot, 0, strpos($bot, ' - '));
    else:
        $bot = substr($bot, 3);
    endif;
    echo $creator . ': ' . $bot . '<br>';
endforeach;