Search code examples
phpstringexplode

How to display first two words from string in div and remaining in other span php?


I want to display string in different div and span, but can't able to do that. I am using below code to do that, but it not works. Can anyone help me solve out problem?

Want to display like this:

Input String: Lorem ispum dolor text si sample dummy text.

Output: Lorem ispum <span> dolor text si sample dummy text.</span>

if(!empty($extraData['heading_text']) && str_word_count($extraData['heading_text']) >= 3) :
  $getwords = explode(" ", $extraData['heading_text']);
  echo $getwords[0].' '.$getwords[1] .' '.'<span>'.$getwords[2]. '</span>';
  unset($getwords[0]);
  unset($getwords[1]);
  unset($getwords[2]);
  echo  implode(" ", array_values($getwords));
else :
  echo $extraData['heading_text']; 
endif;

Solution

  • Well, just extract and output the tokens you are interested in:

    <?php  
    $input = "Lorem ispum dolor text si sample dummy text.";
    preg_match('/^(\w+\s+\w+)\s+(.*)$/', $input, $token);
    echo sprintf("<div>%s</div>\n<span>%s</span>\n", $token[1], $token[2]);
    

    The output obviously is:

    <div>Lorem ispum</div>
    <span>dolor text si sample dummy text.</span>
    

    The same certainly is possible using explode() too, but much more complex:

    <?php
    $input = "Lorem ispum dolor text si sample dummy text.";
    $word = explode(" ", $input);
    echo sprintf("<div>%s %s</div>\n", $word[0], $word[1]);
    unset($word[0]); 
    unset($word[1]);
    echo sprintf("<span>%s</span>\n", implode(" ", $word));
    

    UPDATE:

    The first alternative, based on a regular expression, only works for true "words", that is defined pretty strict. You can somewhat "weaker" that strict behavior by slightly altering the expression:

    <?php  
    $input = "What we've Done";
    preg_match('/^([^\s]+\s+[^\s]+)\s+(.*)$/', $input, $token);
    echo sprintf("<div>%s</div>\n<span>%s</span>\n", $token[1], $token[2]);
    

    With that modification the output again is as expected:

    <div>What we've</div>
    <span>Done</span>