Php substr entire words - php

How can i substr 20 chars from $xbio and get only complete words?
$xbio = 'word1 ord2 word3 word4 and so on';
echo ''.substr($xbio, 0, 20).'...';
TY
Found this searching stackoverflow - tell me what do you think please:
<? $xbio = preg_replace('/\s+?(\S+)?$/', '', substr($xbio, 0, 50)); ?>

This is the function i always use:
# advanced substr
function gen_string($string,$min) {
$text = trim(strip_tags($string));
if(strlen($text)>$min) {
$blank = strpos($text,' ');
if($blank) {
# limit plus last word
$extra = strpos(substr($text,$min),' ');
$max = $min+$extra;
$r = substr($text,0,$max);
if(strlen($text)>=$max) $r=trim($r,'.').'...';
} else {
# if there are no spaces
$r = substr($text,0,$min).'...';
}
} else {
# if original length is lower than limit
$r = $text;
}
return $r;
}

preg_match('/^([a-zA-Z0-9 ]{1,20})\\b/', $xbio, $matches);
echo $matches[1];

This is a function that i use for this kind of task:
function truncate($str, $maxLength, $append = '...') {
if (strlen($str) > $maxLength) {
$str = substr($str, 0, $maxLength);
$str = preg_replace('/\s+.*?$/', '', $str); // this line is important for you
$str = trim($str);
$str .= $append:
}
return $str;
}

Related

How to trim all leading/trailing <br> code using php

I am trying to remove all leading and trailing <br> in a string using PHP.
Here is an example
<br><br>
Hello<br>
World<br>
<p>This is a message<br>...</p>
<br><br><br><br>
I want to return
Hello<br>
World<br>
<p>This is a message<br>...</p>
I tried to do the following
echo trim($str, '<br>');
But it does not remove them. How can I remove the new line html code?
Use preg_replace with the beginning ^ and end $ anchors:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/', '', $string);
Or for multiple lines:
$string = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', $string);
You could also trim() it multiple times:
while($string !== ($string = trim($string, '<br>'))){}
This function does the job. Also applicable to anything else really.
//remove all leading and trailing occurences of needle ($n) from haystack ($h)
function trimAll($h, $n){
if(!$h = trim($h,$n)){
trimAll($h, $n);
}
return $h;
}
I wrote this function that will do the job a little better as it gives me more flexibility on what characters to remove and when this function by default will first remove the leading/trailing characters in order:
any tabs
any new lines
any
any
any tabs
any new lines
function trimString($str, $myList = array("\t","\n", "<br>","<br />", "\t","\n") ){
if( ! is_array($myList) ){
$charsToTrim[] = $chr;
} else {
$charsToTrim = $myList;
}
foreach($charsToTrim as $chr){
$len = strlen($chr);
$nlen = $len * -1;
while( substr($str, 0, $len) == $chr){
$str = trim(substr($str, $len));
}
while( substr($str, $nlen) == $chr){
$str = trim(substr($str, 0, $nlen));
}
}
return $str;
}
to use
// default use case
echo trimString($message);
or
//remove only one string
echo trimString($message, '<br>'); // remove only the leading training '<br>'
or
//remove more than 1 string in order
echo trimString($message, array('<br>'<br />') );
I hope this helps someone out there :)
$p=array(
'<br><br>',
'Hello<br>',
'World<br>',
'<p>This is a message<br>...</p>',
'<br><br><br><br>'
);
function trimdeluxe($str, $sub)
{
$parts=explode($sub, $str);
for ($x=0; $x<2; $x++) {
foreach ($parts as $i=>$v) {
if (!strlen($v)) {
unset($parts[$i]);
} else {
break;
}
}
$parts=array_reverse($parts);
}
return implode($sub,$parts);
}
foreach ($p as $str) {
print $str . ' -> ' . trimdeluxe($str, '<br>') . "\n";
}

PHP: remove word from sentence if it contains #

I want to remove words from sentence if word contains #, I am using php.
Input: Hi I am #RaghavSoni
Output: Hi I am
Thank You.
You could do:
$str = preg_replace('/#\w+/', '', $str);
This is not a good way, but it works :
<?php
$input="Hi I am #RaghavSoni";
$inputWords = explode(' ', $input);
foreach($inputWords as $el)
{
if($el[0]=="#" )
{
$input = str_replace($el, "", $input);
}
}
echo $input;
?>
while(strpos($string, '#') !== false) {
$location1 = strpos($string, "#");
$location2 = strpos($string, " ", $location1);
if($location2 !== false) {
$length = $location2 - $location1;
$string1 = substr($string, 0, $location1);
$string2 = substr($string, $location2);
$string = $string1 . $string2;
}
}
echo $string;
echo str_replace("#RaghavSoni", "", "Hi I am #RaghavSoni.");
# Output: Hi I am.

preg_match and UTF-8 in PHP make hashtag

I have this code:
$text= "#h #gg #مصر";
$get_hash = preg_match_all("/(^|\s)#(\w*[a-zA-Z-أ-إ-آ-ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-لا-لا-لآ-لأ-لإ-ى-ي-ئ-ة-ء-ؤ_]+\w*)/", $text, $matches);
$array_hash = implode("",$matches[0])."";
$hash = str_replace('#', ', ', $array_hash);
echo "hash (".$hash.")<br />";
echo $text;
Result:
hash (, h , gg)
#h #gg #مصر
I want a result like that:
hash (, h , gg , مصر)
#h #gg #مصر
To take whatever in UTF-8 we use this [^ \"\n\r\t<]*
i know its too late just for others to know
i modify this function to make it allow Arabic characters
as fallowing
function get_hashtags($string, $str = 1) {
preg_match_all('/#(\w*[a-zA-Z-أ-إ-آ-ا-ب-ت-ث-ج-ح-خ-د-ذ-ر-ز-س-ش-ص-ض-ط-ظ-ع-غ-ف-ق-ك-ل-م-ن-ه-و-لا-لا-لآ-لأ-لإ-ى-ي-ئ-ة-ء-ؤ_]+)/',$string,$matches);
$i = 0;
if ($str) {
foreach ($matches[1] as $match) {
$count = count($matches[1]);
$keywords .= "$match";
$i++;
if ($count > $i) $keywords .= ", ";
}
} else {
foreach ($matches[1] as $match) {
$keyword[] = $match;
}
$keywords = $keyword;
}
return $keywords;
}
usage :
$string = "<p>#عاشت #فلسطين حرة عربية يوجد 2 هاشتاج لازم اشوفهم في الداتا بيز</p>";
$myArray = get_hashtags($string, $str = 0);
$max = sizeof($myArray);
for($i = 0; $i < $max;$i++)
{
echo "#".$myArray[$i]."<br />";
}
echo "$string"
result
#عاشت
#فلسطين
#عاشت #فلسطين حرة عربية يوجد 2 هاشتاج لازم اشوفهم في الداتا بيز

php substr in html dom

How can I use substr() in a HTML dom? I want keep all the html tags and just shorten the text.
$str = '<div>Today is a nice day</div>';
$part1 = preg_replace("/<a(.*?)>(.*?)<\/a>/i",substr('\\2', 0,10),$str).'...';
$part2 = preg_replace("/<a(.*?)>(.*?)<\/a>/i",'\\2',$str);
echo str_replace($part2,$part1,$str);// nothing change
// I need <div>Today is a...</div>
It could probably be a bit more robust, but this should do the trick:
$str = '<div>Today is a nice day</div>';
echo shortenLinks($str);
function shorten($matches) {
$maxlen = 10;
$str = $matches[2];
if (strlen($str) > $maxlen) {
return "<" . $matches[1] . ">" . substr($str, 0, $maxlen) . "...<";
} else {
return $matches[0];
}
}
function shortenLinks($str) {
$pattern = "/<(a\s+.*)>([^<]+)</";
return preg_replace_callback($pattern, "shorten", $str);
}

Making sure PHP substr finishes on a word not a character

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
substr($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.
You can try this:
$s = substr($string, 0, 261);
$result = substr($s, 0, strrpos($s, ' '));
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);
}
wordwrap and explode then first array element is you want
$wr=wordwrap($text,20,':');
$strs=explode(":",$wr);
$strs[0]
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 );
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;
}
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));
}
$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));
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***....
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;
}
?>

Categories