I am trying to do some PHP programming concepts and I am not aware of some in-build functions. So my doubt is:
In PHP, how to remove slashes from strings? Is there any function available in PHP for this??
e.g.
$string="people are using Iphone/'s instead of Android phone/'s";
You can do a number of things here, but the two approaches I would choose from are:
Use str_replace():
$string = "people are using Iphone/'s instead of Android phone/'s";
$result = str_replace('/','',$string);
echo $result;
// Output: people are using Iphone's instead of Android phone's
If the slashes are backward slashes (as they probably are), you can use stripslashes():
$string = "people are using Iphone\\'s instead of Android phone\\'s";
$result = stripslashes($string);
echo $result;
// Output: people are using Iphone's instead of Android phone's
backslashes need escaping
$newstr = "<h1>Hello \ fred</h1>";
echo str_replace('\\','',$newstr);
If it is a quoted string. Use stripslashes
Heres what I use
function removeSlashes($string = '')
{
return stripslashes(str_replace('/', '', $string));
}
Test
echo $this->removeSlashes('asdasd/asd/asd//as/d/asdzfdzdzd\\hd\h\d\h\dw');
Output
asdasdasdasdasdasdzfdzdzdhdhdhdw
you can use function like
$string = preg_replace ("~/~", "", $string);
Use varian preg
$string="people are using Iphone/'s instead of Android phone/'s";
echo $string = preg_replace('/\//', '', $string);
body, html, iframe {
width: 100% ;
height: 100% ;
overflow: hidden ;
}
<iframe src="https://ideone.com/uIBINP" ></iframe>
I tried this method to remove single forward slashes.
I used str_replace to strip the slashes out. It still did not work for me, I had to go and change all the double quotes in the database to single quotes, update the table, then change it back to double quotes for it to work. Weird.
str_replace('\\', '', $content)
You can use stripslashes() function.
<?php
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>
Related
I've got a simple string that looks like a:104:{i:143;a:5:{s:5:"naz";s:7:"Alb";s:10:"base"}} and I'd like to save all text in quotation mark cleaning it of things like s:5 and stuff using regex. Is this possible?
Want to get everything between quotes? use: ".*" as your search string (escape " characters as required)
..also you can check out http://www.zytrax.com/tech/web/regex.htm for more help with regex. (It's got a great tool where you can test input text, RE, and see what you get out)
As long as the double quotes are matched, the following call
preg_match_all('/"([^"]*)"/',$input_string,$matches);
will give you all the text between the quotes as array of strings in $matches[1]
function session_raw_decode ($data) {
$vars = preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/', $data, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$result = array();
for($i = 0; isset($vars[$i]); $i++)
$result[$vars[$i++]] = unserialize($vars[$i]);
return $result;
}
I have this snippet somewhere found on my server... (no idea from where it is or if I have it written myself)
You can use it and do:
$json = json_encode(session_raw_decode($string));
This should do the job.
I have the following in a variable, |MyString|
I want to strip the leading | and the ending | returning MyString
What is the quickest and non intensive way of doing this?
Easiest way is probably
$result = trim($input, '|');
http://docs.php.net/trim
e.g.
<?php
$in = '|MyString|';
$result = trim($in, '|');
echo $result;
prints MyString
Checkout the str_replace function in PHP http://php.net/manual/en/function.str-replace.php
this should remove all '|' characters:
str_replace('|','',$myString)
You may be able to use a regular expression to only remove the first and last '|' or alternatively using the String trim() function may also work:
http://www.php.net/manual/en/function.trim.php
So, something like this:
$trimmedMyString = trim($myString, "|");
Worth trying anyway.
$varHi I know this is an extremely basic task, but I am some what confused.
I am pulling a String back from a Database and assigning it to $var. I am then outputting this value into a text area. However, when I do, the string is surrounded in " ".
e.g. "This is the String", but I just want : This is the String
I have tried many functions. I am using chr(34) to search for the ", but to no avail. It will only replace them if it is inside the string. Not on the outside / surrounding the string.
$var = str_replace( chr(34), "" ,$var);
Thanks In Advance for any help.
EDIT : Turn's out I was outputting incorrectly into the text area
""
should have been
Thank's for the help.
$var = str_replace( '"', '' ,$var);
See it in action here
$var = str_replace('"', '', $var);
What about $var = str_replace('"', '', $var);?
you could use str_replace, as already mentioned but that would remove quotes from the string body also (if you have any)
to remove only the first and last ones you could use the trim function with the optional second parameter
edit: and if you have quotes inside the string that you want to keep those might be escaped so you might use str_replace to use only the quotes instead the escaped quotes ( str_replace('\"', '"', $string) );
The double speech should only appear if they are in your data being pulled, unless you are echoing or printing to the text area incorectly.
As said above the
$var = str_replace('"', '', $var);
Will work fine, but its a bit of a hack if your data doesn't have the double speech in it to start with.
I am currently building breadcrumb. It works for example for
http://localhost/researchportal/proposal/
<?php
$url_comp = explode('/',substr($url,1,-1));
$end = count($url_comp);
print_r($url_comp);
foreach($url_comp as $breadcrumb) {
$landing="http://localhost/";
$surl .= $breadcrumb.'/';
if(--$end)
echo '
<a href='.$landing.''.$surl.'>'.$breadcrumb.'</a>ยป';
else
echo '
'.$breadcrumb.'';
};?>
But when I typed in http://localhost////researchportal////proposal//////////
All the formatting was gone as it confuses my code.
I need to have the site path in an array like ([1]->researchportal, [2]->proposal)
regardless of how many slashes I put.
So can $url_comp = explode('/',substr($url,1,-1)); be turned into a regular expression to get my desired output?
You don't need regex. Look at htmlentities() and stripslashes() in the PHP manual. A regex will return a boolean value of whatever it says, and won't really help you achieve what you are trying to do. All the regex can let you do is say if the string matches the regex do something. If you put in a regex requiring at least 2 characters between each slash, then any time anyone puts more than one consecutive slash in there, the if statement will stop.
http://ca3.php.net/manual/en/function.stripslashes.php
http://ca3.php.net/manual/en/function.htmlentities.php
Found this on the php manual.
It uses simple str_replace statements, modifying this should achieve exactly what your post was asking.
<?
function stripslashes2($string) {
$string = str_replace("\\\"", "\"", $string);
$string = str_replace("\\'", "'", $string);
$string = str_replace("\\\\", "\\", $string);
return $string;
}
?>
I am writing some JavaScript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?
<script type="text/javascript">
$('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
Quite simply: echo str_replace('\'', '\\\'', $myString);
However, I'd suggest use of JSON and json_encode() function as it will be more reliable (quotes new lines for instance):
<?php $data = array('myString' => '...'); ?>
<script>
var phpData = <?php echo json_encode($data) ?>;
alert(phpData.myString);
</script>
If you want to escape characters with a \, you have addcslashes(). For example, if you want to escape only single quotes like the question, you can do:
echo addcslashes($value, "'");
And if you want to escape ', ", \, and nul (the byte null), you can use addslashes():
echo addslashes($value);
str_replace("'", "\'", $mystringWithSingleQuotes);
In some cases, I just convert it into ENTITIES:
// i.e., $x= ABC\DEFGH'IJKL
$x = str_ireplace("'", "'", $x);
$x = str_ireplace("\\", "\", $x);
$x = str_ireplace('"', """, $x);
On the HTML page, the visual output is the same:
ABC\DEFGH'IJKL
However, it is sanitized in source.
Use the native function htmlspecialchars. It will escape from all special character. If you want to escape from a quote specifically, use with ENT_COMPAT or ENT_QUOTES. Here is the example:
$str = "Jane & 'Tarzan'";
echo htmlspecialchars($str, ENT_COMPAT); // Will only convert double quotes
echo "<br>";
echo htmlspecialchars($str, ENT_QUOTES); // Converts double and single quotes
echo "<br>";
echo htmlspecialchars($str, ENT_NOQUOTES); // Does not convert any quotes
The output would be like this:
Jane & 'Tarzan'<br>
Jane & 'Tarzan'<br>
Jane & 'Tarzan'
Read more in PHP htmlspecialchars() Function
To replace only single quotes, use this simple statement:
$string = str_replace("'", "\\'", $string);
You can use the addcslashes function to get this done like so:
echo addcslashes($text, "'\\");
After a long time fighting with this problem, I think I have found a better solution.
The combination of two functions makes it possible to escape a string to use as HTML.
One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.
Solution:
mysql_real_escape_string(htmlspecialchars($string))
Solve:
a PHP line created to call a JavaScript function like
echo
'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"
I wrote the following function. It replaces the following:
Single quote ['] with a slash and a single quote [\'].
Backslash [\] with two backslashes [\\]
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\'
);
return strtr($target, $replacements);
}
You can modify it to add or remove character replacements in the $replacements array. For example, to replace \r\n, it becomes "\r\n" => "\r\n" and "\n" => "\n".
/**
* With new line replacements too
*/
function escapePhpString($target) {
$replacements = array(
"'" => '\\\'',
"\\" => '\\\\',
"\r\n" => "\\r\\n",
"\n" => "\\n"
);
return strtr($target, $replacements);
}
The neat feature about strtr is that it will prefer long replacements.
Example, "Cool\r\nFeature" will escape \r\n rather than escaping \n along.
Here is how I did it. Silly, but simple.
$singlequote = "'";
$picturefile = getProductPicture($id);
echo showPicture('.$singlequote.$picturefile.$singlequote.');
I was working on outputting HTML that called JavaScript code to show a picture...
I am not sure what exactly you are doing with your data, but you could always try:
$string = str_replace("'", "%27", $string);
I use this whenever strings are sent to a database for storage.
%27 is the encoding for the ' character, and it also helps to prevent disruption of GET requests if a single ' character is contained in a string sent to your server. I would replace ' with %27 in both JavaScript and PHP just in case someone tries to manually send some data to your PHP function.
To make it prettier to your end user, just run an inverse replace function for all data you get back from your server and replace all %27 substrings with '.
Happy injection avoiding!