substr($body, 0, strpos($body, ' ', 260))
Answer from Achshar on Stack Overflowsubstr($body, 0, strpos($body, ' ', 260))
It could be done with a regex, something like this will get up to 260 characters from the start of string up to a word boundary:
$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
$line=$match[0];
}
Alternatively, you could maybe use the wordwrap function to break your $body into lines, then just extract the first line.
Your first approach is fine: Check whether x is contained with strpos and if so get anything after it with substr.
But you could also use strstr:
strstr($str, 'x')
But as this returns the substring beginning with x, use substr to get the part after x:
if (($tmp = strstr($str, 'x')) !== false) {
$str = substr($tmp, 1);
}
But this is far more complicated. So use your strpos approach instead.
Regexes would make it a lot more elegant:
// helo babe
echo preg_replace('~.*?x~', '', $str);
// Tuex helo babe
echo preg_replace('~.*?y~', '', $str);
But you can always try this:
// helo babe
echo str_replace(substr($str, 0, strpos(
str);
// Tuex helo babe
echo str_replace(substr($str, 0, strpos(
str);
If your string has multibyte encoding (like UTF-8) does, you should use mb_substr to avoid problems like this:
$introtext=mb_substr($introtext,0,200);
In case someone tried the previous answers, and it still didn't work:
Try to add a Unicode name in mb_substr like:
$introtext = mb_substr($introtext, 0, 200, 'utf-8');
The most efficient solution is the strtok function:
strtok($mystring, '/')
NOTE: In case of more than one character to split with the results may not meet your expectations e.g. strtok("somethingtosplit", "to") returns s because it is splitting by any single character from the second argument (in this case o is used).
@friek108 thanks for pointing that out in your comment.
For example:
$mystring = 'home/cat1/subcat2/';
$first = strtok($mystring, '/');
echo $first; // home
and
$mystring = 'home';
$first = strtok($mystring, '/');
echo $first; // home
Use explode()
$arr = explode("/", $string, 2);
$first = $arr[0];
In this case, I'm using the limit parameter to explode so that php won't scan the string any more than what's needed.