如何让 str_replace 识别使用 glob(在 Mac 上)检索的文件名中的变音符号?
我正在使用 glob 和下面的代码从目录中读取文件名。
我想迭代它们并用其他字符替换变音字符。
但是,str_replace甚至找不到元音变音字符,因此我假设它们采用其他类型的字符编码。
这在 Windows 上一直有效,但我现在在 Mac 上,所以我尝试使用 iconv 从“macintosh”转换为“UTF-8”,但这不起作用,请参见下文。
如果我在代码中定义一个带有元音变音的字符串,那么 str_replace 会找到元音变音,但在使用 glob()
检索的字符串中却找不到。
如何让 str_replace 识别文件名字符串中的元音变音字符,以便替换它们?
$pathAndFileNames = glob($directory . '/*.php');
if (count($pathAndFileNames) > 0) {
foreach ($pathAndFileNames as $oldName) {
$newName = str_replace('ü', 'ue', $oldName);
echo $newName; //outputs "rücktest.php"
$oldName2 = "rücktest.php";
$newName2 = str_replace('ü', 'ue', $oldName2);
echo $newName2; //outputs "ruecktest.php"
}
}
I'm reading file names out of a directory with glob with the code below.
I want to iterate through them and replace umlaut characters with other characters.
However, str_replace
does not even find the umlaut characters, so I assume they are in some other kind of character encoding.
This has always worked on Windows but I am now on a Mac so I tried to convert from "macintosh" to "UTF-8" with iconv but that didn't work, see below.
If I define a string with umlauts in code, then str_replace finds the umlauts fine but not in the strings retrieved with glob()
.
How can I get str_replace to recognize the umlaut characters in file name strings so I can replace them?
$pathAndFileNames = glob($directory . '/*.php');
if (count($pathAndFileNames) > 0) {
foreach ($pathAndFileNames as $oldName) {
$newName = str_replace('ü', 'ue', $oldName);
echo $newName; //outputs "rücktest.php"
$oldName2 = "rücktest.php";
$newName2 = str_replace('ü', 'ue', $oldName2);
echo $newName2; //outputs "ruecktest.php"
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在我的机器上测试了这段代码(请注意 Ubuntu),没有出现这样的问题。我有一个解决方案供你尝试。确保您的脚本以 UTF-8 编码保存。
当使用 Western-8859-15 编码保存文件时,我可以复制您的问题,但是当使用 UTF-8 编码保存文件时,脚本的行为如您所期望的。
检查您的编辑器首选项并保存为功能。
I tested this code on my machine (Ubuntu mind you) and had no such issue. I have one solution for you to try. Make sure your script is saved with UTF-8 encoding.
I can replicate your issue when saving the file with Western-8859-15 encoding, but when the file is saved with UTF-8 encoding the script behaves as you would expect.
Check your editor preferences and save as functionality.