67

substr関数の使い方は知っていますが、これで単語の途中で文字列が終了します。文字列を単語の終わりで終了させたいのですが、これを行うにはどうすればよいですか?正規表現が含まれますか?どんな助けでも大歓迎です。

これは私がこれまでに持っているものです。ただSubStr...

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

乾杯

4

11 に答える 11

142
substr($body, 0, strpos($body, ' ', 260))
于 2012-06-02T18:16:43.367 に答える
114

これは正規表現で行うことができます。次のようなものは、文字列の先頭から単語境界まで最大 260 文字になります。

$line=$body;
if (preg_match('/^.{1,260}\b/s', $body, $match))
{
    $line=$match[0];
}

または、wordwrap関数を使用して $body を行に分割し、最初の行だけを抽出することもできます。

于 2009-08-05T13:41:05.460 に答える
38

これを試すことができます:

   $s = substr($string, 0, 261);
   $result = substr($s, 0, strrpos($s, ' '));
于 2009-08-05T13:45:46.123 に答える
13

これを行うことができます: 260 番目の文字から最初のスペースを見つけて、それをクロップ マークとして使用します。

$pos = strpos($body, ' ', 260);
if ($pos !== false) {
    echo substr($body, 0, $pos);
}
于 2009-08-05T13:47:06.513 に答える
1
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;
}
于 2013-12-17T01:13:44.477 に答える
1

私はこの解決策を使用します:

$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 );
于 2013-10-29T13:24:55.807 に答える
0
$pos = strpos($body, $wordfind);
echo substr($body,0, (($pos)?$pos:260));
于 2009-08-05T13:47:47.760 に答える
-1
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***....

于 2014-06-14T10:58:40.263 に答える