Posted By

jatkins on 08/10/10


String strings

Versions (?)

Who likes this?

2 people have marked this snippet as a favorite


Get the first two words of a string

 / Published in: PHP

Public domain.

  1. function first_two_words($val) {
  2. $val2 = substr($val, strpos($val, ' ')+1);
  3. $val = substr($val, 0, strlen($val)-strlen($val2)+strpos($val2, ' '));
  4. return $val;
  5. }

Report this snippet  


RSS Icon Subscribe to comments
Posted By: james0rion on August 10, 2010

It seems to me that using preg_split or even explode with a limit of 3 would be the ideal solution.

Then return "$array[0] $array[1]";


function firsttwowords($string) { $array = explode(' ', $string, 3); return "$array[0] $array[1]"; }

Posted By: jatkins on October 25, 2010

Yeah, that's a shorter way of doing it. The only reason for me using the string functions was to find a way to do it without having to store it in an array first, but it doesn't really matter which method you use.

You need to login to post a comment.