用于标识各种空格的正则表达式,这些空格将用作分隔符,用于将字符串展开为数组


Regex for identifying all kinds of spaces to be used as a delimiter for exploding a string into an array?

我不熟悉正则表达式,所以当我需要识别一个段落(Wordpress中的帖子摘录)是否以单词"by"开头,如果它确实应用CSS类到单词"by"和接下来的两个单词时,我通过将字符串展开成一个由空格分隔的数组,操作数组,然后将其内爆来实现。

但是有些奇怪的事情正在发生。分隔符"并不适用于所有空格(并且没有使用双空格)。是否存在多个版本的空格字符?

我的整个网站不应该有相同的编码类型,因此只有一个空格字符?

如果我编辑其中一个问题帖子并删除前两个空格并用新空格替换它们,代码可以正常工作。

我的代码如下(我知道我声明了很多变量):elseif{下面的部分是我具体描述的,但我粘贴了整个条件块供参考。

$byLine = strtolower(string_limit_words(get_the_excerpt(),1));
$storySnippet = string_limit_words(get_the_excerpt(),16);
$storyExplode = explode(' ', $storySnippet);
if (($byLine=="by") && strtolower($storyExplode[3])=="and") {
    $storySlice = array_slice($storyExplode, 6);
    $storyLast = implode(' ', $storySlice); ?>
    <a href="<?php the_permalink(); ?>" class="byline">
    <?php echo string_limit_words(get_the_excerpt(),6); ?></a>
    <?php echo "  ".$storyLast."&hellip;";
} elseif ($byLine=="by") {
    $storySlice = array_slice($storyExplode, 3);
    $storyLast = implode(' ', $storySlice); ?>
    <a href="<?php the_permalink(); ?>" style="color:#888;font-style:italic;font-size:90%;">
    <?php echo string_limit_words(get_the_excerpt(),3); ?></a>
    <?php echo"  ".$storyLast."&hellip;";
}  else { 
    echo string_limit_words(get_the_excerpt(),16)."&hellip;"; 
}
编辑:

目前使用preg_split('|'s+|', $storySnippet)而不是用' '爆炸数组,但我仍然遇到同样的问题。

在adovatedaily.com上直播,页面中间"观点"栏下的第三个条目。

EDITx2:

将一个问题字符串转换为十六进制。"By Jen"转换为4279c2a04a656e。没有20在那里,似乎有一个额外的字符。到底发生了什么事?

多亏了这些注释,我发现导致问题的空格是一个非换行空格(十六进制中的c2a0)。

我成功地用下面一行的常规空格替换了字符串的空白,解决了问题。

$spacedExcerpt = preg_replace('/'xC2'xA0/', ' ', get_the_excerpt());

您可以使用:

preg_split('|'s+|', $storySnippet);

匹配任何空白字符。