php 从php中的字符串中删除单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3903219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing single-quote from a string in php
提问by micahmills
I have an HTML form that a user can input text into a title
field, I then have php creating an HTML file called title.html
我有一个 HTML 表单,用户可以在一个title
字段中输入文本,然后我让 php 创建一个名为的 HTML 文件title.html
My problem is that users can input spaces and apostrophes into the title field that can't be used in the html file name. I replaced the spaces with underscores by using:
我的问题是用户可以将空格和撇号输入到 html 文件名中不能使用的标题字段中。我用下划线替换了空格:
$FileName = str_replace(" ", "_", $UserInput);
However, I can't seem to remove single-quotes? I have tried using:
但是,我似乎无法删除单引号?我试过使用:
$FileName = preg_replace("/'/", '', $UserInput);
but this took test's
and turned it into test\s.html
.
但这test's
把它变成了test\s.html
.
回答by hookedonwinter
Using your current str_replace method:
使用您当前的 str_replace 方法:
$FileName = str_replace("'", "", $UserInput);
While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.
虽然很难看出,但第一个参数是双引号后跟单引号后跟双引号。第二个参数是两个双引号,中间没有任何内容。
With str_replace, you could even have an array of strings you want to remove entirely:
使用 str_replace,您甚至可以拥有要完全删除的字符串数组:
$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example
$FileName = str_replace( $remove, "", $UserInput );
回答by Gilles Quenot
You can substitute in HTML entitiy:
您可以在 HTML 实体中替换:
$FileName = preg_replace("/'/", "\'", $UserInput);
回答by Jeremy
You could also be more restrictive in removing disallowed characters. The following regex would remove all characters that are not letters, digits or underscores:
您还可以更严格地删除不允许的字符。以下正则表达式将删除所有不是字母、数字或下划线的字符:
$FileName = preg_replace('/[^\w]/', '', $UserInput);
You might want to do this to ensure maximum compatibility for filenames across different operating systems.
您可能希望这样做以确保跨不同操作系统的文件名的最大兼容性。
回答by Faisal
Try this one. You can strip just '
and "
with:
试试这个。你可以只剥除'
并"
用:
$FileName = str_replace(array('\'', '"'), '', $UserInput);
回答by Neo
$replace_str = array('"', "'", ",");
$FileName = str_replace($replace_str, "", $UserInput);
回答by isaiasmac
I used this function htmlspecialcharsfor alt attributes in images
我将此函数htmlspecialchars用于图像中的 alt 属性
回答by Milind Morey
$test = "{'employees':[{'firstName':'John', 'lastName':'Doe'},{'firstName':'John', 'lastName':'Doe'}]}" ;
$test = str_replace("'", '"', $test);
echo $test;
$jtest = json_decode($test,true);
var_dump($jtest);