times-kzm

life log

phpで単語境界を考慮したsubstring

関数

<?php

function truncate($content, $len) {
  $pos = strpos($content, ' ', $len);
  return substr($content, 0, $pos);
}

結果

<?php

$content = 'The English Wikipedia is the English-language edition of the free online encyclopedia Wikipedia. Founded on 15 January 2001, it is the first edition of Wikipedia and, as of April 2019, has the most articles of any edition.';

echo truncate($content, 1), PHP_EOL;
//  3: The

echo truncate($content, 5), PHP_EOL;
// 11: The English

echo truncate($content, 12), PHP_EOL;
// 21: The English Wikipedia