Skip to content
Advertisement

Parse and reformat text with optionally occurring trailing characters

Due to horrible and inconsistent formatting by a certain website we are receiving data from, I need to parse the following string and print new strings after replacing/removing one or two substrings.

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

Desired result:

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

How can I parse a line with two ‘-‘ into the corresponding Owner: name format?

My current code:

$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>';
}

Advertisement

Answer

This will definitely fail in the future, because of the inconsistent format the data is being delivered in, but hey, at least it works now.

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;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement