[英]Can't find word with Quotation mark in text file on php
我有一個文本文件,我想檢查該文件是否包含字符串wor"dddddd
。讓我們假設這是文本文件的內容:
...,sometext,moretext,wor"dddddd,867767,3468647,sometext,...
這是我的代碼,我不知道為什么它不起作用(打印8而不是3):
<?php
$id='wor\"dddddd';
$fopen = fopen("file.txt", 'r');
$content= htmlspecialchars(file_get_contents("file.txt"));//
$split=explode(",", $content);
$arr_len=count($split);
$pos=0;
$result=array();
//finding the position of the word in the array
foreach ($split as $x){
if(stripos($id, $x)!==false) {
break;}
$pos++;
}
echo $pos;//should print 3, but it prints 8 i.e it's not find the word wor"dddddd
?>
我不知道為什么單詞中找不到引號,我試圖添加反斜杠\\
(代碼中的第2行),但是輸出仍然是8。如果知道要在文本文件中找到的單詞是否包含引號,該怎么辦?
在這里您有幾個錯誤。
首先,在字符串中
$id='wor\"dddddd';
您不需要在單引號字符串中轉義"
。因此,您嘗試查找'wor\\"dddddd'
而不是'wor"dddddd'
。很明顯,這不會發生。
下一個錯誤來自使用htmlspecialchars
。
該功能將引號變成html-entities,因此您不必wor"dddddd
而是” wor"dddddd
wor"dddddd
。再次,您可以找到wor"dddddd
wor"dddddd
。
因此,解決方案:
$id = 'wor"dddddd';
$content= file_get_contents("file.txt");
// following lines remain unchanged
獎勵:您可以用以下一行替換$split
上的循環:
$pos = array_search($id, $split);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.