【问题标题】:php substr returning incorrect characters on a string variable from a preg_match functionphp substr 从 preg_match 函数返回字符串变量上的不正确字符
【发布时间】:2012-06-09 22:28:16
【问题描述】:

这是一个菜鸟问题,但是...

我正在另一个 php 文件中调用一个函数,该函数使用 preg_match 来获取字符串。然后我想使用 substr 来获取该字符串的特定部分,但是它不输出字符串中的任何字符。当我从 preg_match 函数中替换变量时,我得到了正确的输出。

这是基本代码:

$title = $stream["song1"]; // From a preg_match in an external php file
echo $title; // Correctly prints the song name, in this case "mySong"
echo substr($title, 0, 1);  // Outputs a "<" symbol (why??)

如果我运行上面相同的三行,但对歌曲标题进行硬编码:

$title = "mySong";
echo $title; // Correctly prints the song name, in this case "mySong"
echo substr($title, 0, 1);  // Outputs a "m" symbol (correct)

另外,当我检查变量$title 的类型时,它返回“字符串”。我确定我在做一些非常愚蠢的事情......有人可以帮忙吗?

【问题讨论】:

  • 尝试检查 $stream["song1"] 的编码。也许它包含多字节字符串,您需要使用 mb_substr。试试 strlen($stream["song1"]);

标签: php


【解决方案1】:

似乎$title 包含html标签,因此第一个字符将是&lt;

使用htmlentities() 回显完整的输出,然后您应该能够看到您实际在寻找字符串的哪一部分。

echo htmlentities($title);

或者,您可以使用 strip_tags() 简单地从字符串中删除所有 html 标记:

$title = strip_tags($title);
echo substr($title, 0, 1); // should work

【讨论】:

    猜你喜欢
    • 2017-08-07
    • 1970-01-01
    • 2016-03-28
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    相关资源
    最近更新 更多