Как проверить, существует ли пунктуация в заданном количестве символов и не обрезает ли она там текст - PHP? - PullRequest
1 голос
/ 27 мая 2020

I wi sh, чтобы проверить, есть ли точка или вопросительный знак (например, две иглы) в первых 100 символах отрывка. Если он есть, то отрывок будет обрезан до полной остановки, иначе он будет обрезан на 100 символов.

Теперь у меня есть следующее, которое проверяет положение иглы: если она ниже 100 символов, то отрывок обрезается там, иначе отрывок сокращается до 100 символов с помощью «...». Проблема в том, что я использую sh для проверки наличия нескольких игл, я пробовал различные методы, такие как цикл и preg_match, но ни один из них не работал. Очень новичок в php, поэтому приветствуются любые указатели.

<?php 
    ob_start();
    the_excerpt();
    $excerpt = ob_get_clean();
    $excerpt = preg_replace('/<.*?>/', '', $excerpt);;
    ?>
    <?php 

    $needle = '.';
    $position = stripos($excerpt, $needle);

    if($position < 100) {
        $offset = $position + 0;
        $position2 = stripos ($excerpt, $needle, $offset);
        $first_two = substr ($excerpt, 0, $position2);
        echo $first_two . '.';
    }

    else {
        $cut = substr( $excerpt, 0, 100 );

        $excerpt = substr( $cut, 0, strrpos( $cut, ' ' ) ) . '...';

        echo $excerpt;
    }        
?>

Ответы [ 4 ]

2 голосов
/ 27 мая 2020

Я бы попробовал что-то подобное. Он требует меньших петель и позволяет легко добавлять иглы. Сразу же сократите строку до 100 символов. Больше не будет, искать по всей строке не нужно.

<?php 
    ob_start();
    the_excerpt();
    $excerpt = ob_get_clean();  

    $maxLength = 100;
    $excerpt   = substr(preg_replace('/<.*?>/', '', $excerpt), 0, $maxLength);

    $needles    = ['.','?'];
    $offset     = min($maxLength, strlen($excerpt));
    $lnf        = $offset; // to store last needle found

    for ($index = 0; $index < $offset; $index++) {
      if (in_array($excerpt[$index], $needles)) {
         $lnf = $index + 1;
      }
    } 

    $excerpt = substr($excerpt, 0, $lnf);

    ?>
1 голос
/ 27 мая 2020

Вы хотите иметь последнее вхождение needle или все вхождения?

// dont use the buffering, there is also a get_the_excerpt function
$excerpt = get_the_excerpt();
$needle = '.';

// use strrpos to get the last occurrence or strpos to get the first
$needle_pos = strrpos(substr($excerpt,0,100), $needle);
if($needle_pos !== false) {
   // we have a needle, so lets change the excerpt
   $excerpt = substr($excerpt, 0, $needle_pos);
}

echo substr($excerpt, 0, 100) . '..'; // when its already cut it is less then 100 chars

Или, что еще лучше, вы могли бы изучить использование фильтров. Фильтр - это что-то из Wordpress. Повсюду в коде Wordpress есть вызовы функций на apply_filters([somename], $somevariable). Он выполнит все функции, связанные с этим тегом [somename], предоставив $somevariable и сохранив там возвращаемое значение. Вы можете добавлять свои собственные фильтры, используя add_filter([somename], [some callback]). Например:

add_filter('the_excerpt', cutoffExcerpt);

function cutoffExcerpt($excerpt) {
    $needle = '.';

    // use strrpos to get the last occurrence or strpos to get the first
    $needle_pos = strrpos(substr($excerpt,0,100), $needle);
    if($needle_pos !== false) {
       // we have a needle, so lets change the excerpt
        $excerpt = substr($excerpt, 0, $needle_pos);
    }

    return substr($excerpt, 0, 100) . '..'; // when its already cut it is less then 100 chars
}

Вы должны добавить это в свой файл functions. php в своей теме (или создать этот файл, если у вас его еще нет). Теперь, когда вы используете the_excerpt() в своем шаблоне, он будет отрезан на игле без лишних хлопот.

1 голос
/ 27 мая 2020

Это очень просто с регулярным выражением.

  • Сопоставьте все иглы . , ! , ? , , и ; . Конечно, вы можете добавить больше удаления руды.
  • Флаг PREG_OFFSET_CAPTURE указывает позицию, где он был найден
  • итерация по результатам в обратном направлении
  • возьмите ту с <= 100 и вырежьте оттуда. </li>
$lorem = 'Shields up, sub-light advice! The pathway dies mind like a solid klingon. The space is tightly biological. C-beams walk on beauty at earth!';

$matches = [];
preg_match_all('/\.|\!|\?|,|;/', $lorem, $matches, PREG_OFFSET_CAPTURE);
for($i = count($matches[0])-1; $i >= 0; $i--) {
    echo $matches[0][$i][1], PHP_EOL;
    if($matches[0][$i][1] <= 100) {
        echo "cutting at ", $matches[0][$i][1], PHP_EOL;
        $excerpt = substr($lorem, 0, $matches[0][$i][1] + 1) . ' ...';
        break;
    }
}
echo $excerpt, PHP_EOL;

Вывод

138
105
72
резка на 72

окончательный результат будет

Поднимите щиты, совет по субсвету! Путь умирает умом, как solid клингон. ...

Конечно, вы можете удалить эхо, они просто помогают понять, что происходит.

0 голосов
/ 27 мая 2020

используйте PHP explode () для торможения игл

$excerpt  = "The trees, therefore, must be such old and primitive techniques that they thought nothing of them, deeming them so inconsequential that even savages like us would know of them and not be suspicious. At that, they probably didn't have too much time after they detected us orbiting and intending to land. And if that were true, there could be only one place where their civilization was hidden.";
$needles=['.','?',','];
$str=[$excerpt];
for($i=0;$i<sizeof($needles);$i++) {
    if($i!=0){
        $str[0] .= $needles[$i-1];
    }
    $str=explode($needles[$i],$str[0]);
}

if(strlen($str[0])<100){
    $excerpt=$str[0];
}
else{
    $excerpt=substr($excerpt,0,100);
    $excerpt .= "...";
}
echo $excerpt;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...