substr関数の使い方は知っていますが、これで単語の途中で文字列が終了します。文字列を単語の終わりで終了させたいのですが、これを行うにはどうすればよいですか?正規表現が含まれますか?どんな助けでも大歓迎です。
これは私がこれまでに持っているものです。ただSubStr...
echo substr("$body",0,260);
乾杯
substr($body, 0, strpos($body, ' ', 260))
これは正規表現で行うことができます。次のようなものは、文字列の先頭から単語境界まで最大 260 文字になります。
$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
$line=$match[0];
}
または、wordwrap関数を使用して $body を行に分割し、最初の行だけを抽出することもできます。
これを試すことができます:
$s = substr($string, 0, 261);
$result = substr($s, 0, strrpos($s, ' '));
これを行うことができます: 260 番目の文字から最初のスペースを見つけて、それをクロップ マークとして使用します。
$pos = strpos($body, ' ', 260);
if ($pos !== false) {
echo substr($body, 0, $pos);
}
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;
}
私はこの解決策を使用します:
$maxlength = 50;
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount );
またはインライン:
substr($name, 0, ($spos = strpos($name, ' ', $lcount = count($name) > 50 ? $lcount : 50)) ? $spos : $lcount );
$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;
}
この文字列を関数Strip_text("Long text with html tag or without html tag", 15) に渡します 。この関数は、html タグのない html 文字列から最初の 15 文字を返します。文字列が 15 文字未満の場合、完全な文字列を返します。それ以外の場合は、$lastString パラメータ文字列で 15 文字を返します。
例:
Strip_text("<p>vijayDhanasekaran</p>", 5)
結果:ビジェイ
Strip_text("<h1>vijayDhanasekaran<h1>",5,"***....")
結果: vijay***....