示例标题:动漫标题:第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;