Hi all,

I am trying to work out how to apply css formatting to the first two words in a string.

I have a foreach statement:

$tags = explode('-',$row_IncidentLookup['OutCome']);

foreach($tags as $key) {    
echo $key.'<br/>';
}

The explode uses "-" to split each comment on to a new line.

the result looks like this (example):

John Doe this a a test comment
Jane Doe this is another test comment
Dave Doe and another test comment

Is it possible to use CSS to format the first two words with different colour.

Any help would be great.

Cheers, BlackBox

    It is possible, but it depends on how you define a "word". If we just keep it simple and say a word is separated by spaces (these look like names though, not words, which can get tricky***) then you could do something like this:

    $tags = explode('-',$row_IncidentLookup['OutCome']);
    
    foreach($tags as $key) {    
    $words = explode(' ', $key); //Separate by space like I mentioned above
    echo '<span class="class">'.$words[0].' '.$words[1].'</span>'.implode(' ', array_slice($words, 2)).'<br />'; }

    Note the above is not tested so I may have made a mistake, but you probably get the general idea: you split up the $key variable by spaces to find the first two, and then remove those two from the array before putting them back together again (so you're not repeating them) into a string. Check out [man]array_slice/man for more info.

    *** The reason names can be tricky is not all names are separated by spaces or are "one word". For example a lot of last names have multiple words like "van Gogh" (Vincent van Gogh, the famous painter). While these may be a minority they should still be considered.

      Hi Bonsnap,

      That's a starting point, I will have a play.

      Many thanks, I will let you know how I get on.

      Cheers,

      BlackBox

        Hi Bonesnap,

        Perfect, many thanks for your help.

        Cheers,
        BlackBox

          Write a Reply...