简体   繁体   English

为什么我的search()无法找到特殊字符?

[英]Why is my search() unable to find special characters?

I think this is a character encoding problem. 我认为这是一个字符编码问题。 My javascript search fails to identify a string whenever the string contains certain special characters such as ()* parenthesis, asterisks, and numerals. 每当字符串包含某些特殊字符(例如()*括号,星号和数字)时,我的JavaScript搜索都无法识别该字符串。

The javascript is fairly simple. javascript非常简单。 I search a string (str) for the value (val): 我在字符串(str)中搜索值(val):

n = str.search(val);

The string I search was written to a txt file using PHP... 我使用PHP将搜索到的字符串写入txt文件...

$scomment = $_POST['order'];
$data = stripslashes("$scomment\n");
$fh = fopen("comments.txt", "a");
fwrite($fh, $data);
fclose($fh);

...then retrieved with PHP... ...然后用PHP检索...

$search = $_GET["name"];
$comments = file_get_contents('comments.txt');
$array = explode("~",$comments);
foreach($array as $item){if(strstr($item, $search)){
echo $item;  } }

...and put into my HTML using AJAX... ...并使用AJAX放入我的HTML ...

xmlhttp.open("GET","focus.php?name="+str,true);
xmlhttp.send();

My HTML is encoded as UTF-8. 我的HTML编码为UTF-8。

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

The problem is that the when I search() for strings, special characters are not recognized. 问题是当我在search()中搜索字符串时,无法识别特殊字符。

I didn't really see an option to encode the PHP created text, so I assumed it was UTF-8 too. 我没有真正看到对PHP创建的文本进行编码的选项,因此我认为它也是UTF-8。 Is that assumption incorrect? 这个假设不正确吗?

If this is an encoding problem, how do I change the encoding of the txt file written with PHP? 如果这是一个编码问题,如何更改用PHP编写的txt文件的编码? If it is caused by the above code, where is the problem? 如果是由上述代码引起的,那么问题出在哪里?

The search() function takes a regex. search()函数使用正则表达式。 If a string is given, it is converted into one. 如果给出字符串,则将其转换为一个。 Because of this, any special characters have special meanings, and it will not work as expected. 因此,任何特殊字符都具有特殊含义,并且无法按预期工作。 You need to escape special characters. 您需要转义特殊字符。

Syntax 句法

str. 海峡 search (regexp) 搜索 (正则表达式)

Parameters 参量

regexp 正则表达式

A regular expression object. 正则表达式对象。 If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj). 如果传递了非RegExp对象obj,则使用新的RegExp(obj)将其隐式转换为RegExp。

If you want to search for text, use str.indexOf() instead, unless you NEED a regex. 如果要搜索文本,请改用str.indexOf() ,除非需要正则表达式。 If so, see here on how to escape the string: Is there a RegExp.escape function in Javascript? 如果是这样,请参见此处如何转义字符串: Javascript中是否存在RegExp.escape函数?

Include this function in your code: 在您的代码中包括以下功能:

function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM