Making sure PHP substr finishes on a word not a character

PhpSubstring

Php Problem Overview


I know how to use the substr function but this will happy end a string halfway through a word. I want the string to end at the end of a word how would I go about doing this? Would it involve regular expression? Any help very much appreciated.

This is what I have so far. Just the SubStr...

echo substr("$body",0,260);

Cheers

Php Solutions


Solution 1 - Php

substr($body, 0, strpos($body, ' ', 260))

Solution 2 - Php

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.

Solution 3 - Php

You can try this:

   $s = substr($string, 0, 261);
   $result = substr($s, 0, strrpos($s, ' '));

Solution 4 - Php

You could do this: Find the first space from the 260th character on and use that as the crop mark:

$pos = strpos($body, ' ', 260);
if ($pos !== false) {
    echo substr($body, 0, $pos);
}

Solution 5 - Php

wordwrap and explode then first array element is you want $wr=wordwrap($text,20,':'); $strs=explode(":",$wr); $strs[0]

Solution 6 - Php

I use this solution:

$maxlength = 50;
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount );

Or inline:

substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > 50 ? $lcount : 50)) ? $spos : $lcount );

Solution 7 - Php

function substr_word($body,$maxlength){
    if (strlen($body)<$maxlength) return $body;
    $body = substr($body, 0, $maxlength);
    $rpos = strrpos($body,' ');
    if ($rpos>0) $body = substr($body, 0, $rpos);
    return $body;
}

Solution 8 - Php

What about this?

/**
 * @param string $text
 * @param int $limit
 * @return string
 */
public function extractUncutPhrase($text, $limit)
{
    $delimiters = [',',' '];
    $marks = ['!','?','.'];

    $phrase = substr($text, 0, $limit);
    $nextSymbol = substr($text, $limit, 1);


    // Equal to original
    if ($phrase == $text) {
        return $phrase;
    }
    // If ends with delimiter
    if (in_array($nextSymbol, $delimiters)) {
        return $phrase;
    }
    // If ends with mark
    if (in_array($nextSymbol, $marks)) {
        return $phrase.$nextSymbol;
    }

    $parts = explode(' ', $phrase);
    array_pop($parts);

    return implode(' ', $parts); // Additioanally you may add ' ...' here.
}

Tests:

public function testExtractUncutPhrase()
{
    $stringUtils = new StringUtils();

    $text = 'infant ton-gue could make of both names nothing';
    $phrase = 'infant';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 12));

    $text = 'infant tongue5';
    $phrase = 'infant';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 11));
    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 7));
}

public function testExtractUncutPhraseEndsWithDelimiter()
{
    $stringUtils = new StringUtils();

    $text = 'infant tongue ';
    $phrase = 'infant tongue';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));

    $text = 'infant tongue,';
    $phrase = 'infant tongue';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}

public function testExtractUncutPhraseIsSentence()
{
    $stringUtils = new StringUtils();

    $text = 'infant tongue!';
    $phrase = 'infant tongue!';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 14));
    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 100));

    $text = 'infant tongue!';
    $phrase = 'infant tongue!';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));

    $text = 'infant tongue.';
    $phrase = 'infant tongue.';

    $this->assertEquals($phrase, $stringUtils->extractUncutPhrase($text, 13));
}

Solution 9 - Php

$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));

Solution 10 - Php

public function Strip_text($data, $size, $lastString = ""){
	$data = strip_tags($data);			
	if(mb_strlen($data, 'utf-8') > $size){
		$result = mb_substr($data,0,mb_strpos($data,' ',$size,'utf-8'),'utf-8');
			if(mb_strlen($result, 'utf-8') <= 0){
			$result = mb_substr($data,0,$size,'utf-8');
			$result = mb_substr($result, 0, mb_strrpos($result, ' ','utf-8'),'utf-8');;			
		}
		if(strlen($lastString) > 0) {
			$result .= $lastString;
		}
	}else{
	$result = $data;
	}
	return $result;	
}

Pass the string into funtion Strip_text("Long text with html tag or without html tag", 15) Then this function will return the first 15 character from the html string without html tags. When string less than 15 character then return the full string other wise it will return the 15 character with $lastString parameter string.

Example:

Strip_text("<p>vijayDhanasekaran</p>", 5)

Result: vijay

Strip_text("<h1>vijayDhanasekaran<h1>",5,"***....")

Result: vijay***....

Solution 11 - Php

Try This Function..

<?php
/**
 * trims text to a space then adds ellipses if desired
 * @param string $input text to trim
 * @param int $length in characters to trim to
 * @param bool $ellipses if ellipses (...) are to be added
 * @param bool $strip_html if html tags are to be stripped
 * @param bool $strip_style if css style are to be stripped
 * @return string
 */
function trim_text($input, $length, $ellipses = true, $strip_tag = true,$strip_style = true) {
    //strip tags, if desired
    if ($strip_tag) {
        $input = strip_tags($input);
    }
	
	//strip tags, if desired
    if ($strip_style) {
        $input = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$input);
    }
	
	if($length=='full')
	{
 
 		$trimmed_text=$input;

	}
	else
	{
    	//no need to trim, already shorter than trim length
    	if (strlen($input) <= $length) {
        return $input;
    	}
  
    	//find last space within length
    	$last_space = strrpos(substr($input, 0, $length), ' ');
   	 	$trimmed_text = substr($input, 0, $last_space);
  
    	//add ellipses (...)
    	if ($ellipses) {
        $trimmed_text .= '...';
    	}		
	}
  
    return $trimmed_text;
}
?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCool Hand LukeView Question on Stackoverflow
Solution 1 - PhpAchsharView Answer on Stackoverflow
Solution 2 - PhpPaul DixonView Answer on Stackoverflow
Solution 3 - PhpZedView Answer on Stackoverflow
Solution 4 - PhpGumboView Answer on Stackoverflow
Solution 5 - PhpBatbekh BatmagnaiView Answer on Stackoverflow
Solution 6 - PhpOleksandr KnygaView Answer on Stackoverflow
Solution 7 - PhpSanneView Answer on Stackoverflow
Solution 8 - PhpIvan ProskuryakovView Answer on Stackoverflow
Solution 9 - Phpandres descalzoView Answer on Stackoverflow
Solution 10 - PhpvijayView Answer on Stackoverflow
Solution 11 - PhpEdwin ThomasView Answer on Stackoverflow