Название примера: Название аниме: Эпизод 01, Субб. 01
Привет, я пытаюсь получить "Эпизод 01" в названии, но у меня возникают проблемы с функцией substr(), как я могу объявить команду на нем?
$Updated = get_the_title();
if ( strpos( $Updated , ":" ) && ( strripos( $Updated, "," ) ) ) {
// this is the line I'm having trouble to deal with
$Updated = substr( $Updated , strpos( $Updated , ":" ) + 1 );
} else if ( strpos( $Updated , ":" ) ) {
$Updated = substr( $Updated , strpos( $Updated , ":" ) + 1 );
}
Технически это не вопрос WP, и его, вероятно, следует задавать на PHP или общем форуме программирования.
Что я могу собрать из кода вы предоставляете является то, что вы считаете, что всегда будет двоеточие :
и иногда может быть запятой ,
вы можете захотеть взглянуть на expode()
, а не substr()
+ strpos()
.
Во-первых, чтобы ответить на ваш вопрос, вам понадобится местоположение запятой, чтобы вы могли указать substr()
где остановиться.
$updated = get_the_title();
// calculate the string positions once rather than multiple times
// first colon
$colon_pos = strpos( $updated, ':' );
// first comma AFTER the colon
$comma_pos = strpos( $updated, ',', $colon_pos );
// MUST compare strpos values to false, it can return 0 (zero) which is falsy
if ( $colon_pos !== false && $comma_pos !== false ) {
// start from the colon position plus 1
// use comma position as the length, since it is based on the offset of the colon
$updated = substr( $updated, $colon_pos + 1, $comma_pos );
} else if ( $colon_pos !== false ) {
$updated = substr( $updated, $colon_pos + 1 );
}
Как уже упоминалось в начале, все это можно было бы упростить с помощью explode()
:
// - first, split the title on the first colon ':', the second/last item of
// that action will be everything after the colon if there is a colon, or
// the whole title if there is no colon
// - second, grab that last item and split it on commas, the first/zeroth
// item of that action will be the episode
// - finally, trim off the excess whitespace
$updated = explode( ':', get_the_title(), 2 );
$updated = trim( explode( ',', end( $updated ) )[0] );
Длинная форма:
$updated = get_the_title(); // the full title string
$updated = explode( ':', $updated, 2 ); // split it in two around the first ':'
$updated = end( $updated ); // grab the last element of the split
$updated = explode( ',', $updated ); // split the remainder on ','
$updated = trim( $updated[0] ); // get the first item after the split and remove excess whitespace
Надеюсь, что это не слишком смущает.
Вы можете использовать вспомогательную функцию следующим образом:
function.php
:
function get_string_between($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
template_file.php
:
$Updated = get_the_title();
$Updated = get_string_between($Updated , ":", ",");
echo $Updated;