是的,问题是连字符。WordPress将带空格的连字符转换为短划线。以下是使用WordPress使用连字符进行的转换:
Foo{3连字符,间隔}条→ Foo-Bar(em破折号)
Foo{3个连字符,无空格}条→ Foo Bar(em破折号)Foo{2个连字符,间隔}条→ Foo-Bar(em破折号)Foo{2个连字符,无空格}条→ Foo–Bar(短划线)Foo{1连字符,间隔}条→ Foo–Bar(短划线)参考
here 为了这个。
对于您的特定问题,您可以执行以下操作。这有一个限制,即日期应在标题的最后一个。
// WP converts hyphens with spaces to n-dash, so convert them to hyphen again.
$title = str_replace( array( \' \', \' \', \'–\', \'–\', \'—\', \'—\' ), \'-\', get_the_title() );
// Explode using hyphen;
$title = explode( \'-\', $title );
// Remove last element i.e date.
array_pop( $title );
// Convert array to string.
$title = implode( $title );
// Echo.
echo $title;
或者您可以使用类似以下的regex执行相同的操作,但不受上述限制:
// WP converts hyphens with spaces to n-dash, so convert them to hyphen again.
$title = str_replace( array( \' \', \' \', \'–\', \'–\', \'—\', \'—\' ), \'-\', get_the_title() );
// Pattern for date with hyphen and space.
$pattern = \'(\\s\\W\\s\\d+)\';
// Replace with space.
echo preg_replace( $pattern, \' \', $title );