rtrim not working string with html elements - php

I have a problem with rtrim() function in php. I have string like this one:
$str = "<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],";
Like this, embed the string in array.
I want to remove that last comma in this string. rtrim not working.
When i remove that html elements from that string, rtrim() works perfectly. anyone help?

you have to change your string like this, then it will work, it does not work because your string is inappropriate:
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of
Collateral</a> [2017-04-01],";
echo rtrim($str,",");
output is:
Picture of Collateral [2017-04-01]
The only difference is that double quoted strings interpret embedded variables and a number of escape sequences, while single quoted strings do not. E.g.:
Reference: When should you use single or double quotes in PHP?

write your code below it works
you have write string ""(double quote) and under string you also used "" string instead of this you use ''(single quote);
<?php
$str = "<a id='AccountDocument_11' href='/view/id/11'>Picture of Collateral</a> [2017-04-01],";
echo rtrim($str,",");

i believe you quoted the string wrong.
try the below:
$str = rtrim('<a id="AccountDocument_11" href="/view/id/11">Picture of Collateral</a> [2017-04-01],',',');
echo $str;

Related

PHP convert an octal characters to string

Title is pretty much self explanatory...
How do I echo an octal string ?
I tried :
<?php
echo '\047\131\145\141\162\040\072\040\047'.'<br>';
echo decoct('\047\131\145\141\162\040\072\040\047').'<br>';
echo decoct('047').decoct('131').decoct('145').decoct('141').decoct('162').decoct('040').decoct('072'),decoct('040').decoct('047').'<br>';
?>
but nothing is working for me....
I'm quite sure that some small tweak is needed here but... which one?
Thanks!
Escape sequences are only processed inside double quoted strings, not single-quoted strings.
echo "\047\131\145\141\162\040\072\040\047".'<br>';
This a backslash escaped string, so use stripcslashes() to un-escape, like this:
$escaped = '\047\131\145\141\162\040\072\040\047'.'<br>';
$unescaped = stripcslashes($escaped);
echo $unescaped;
Result:
'Year : '<br>
This may help
function convertOctalToCharacter($octal) {
return chr(octdec($octal[1]));
}
For a mass-tokenizing of strings with octals,
this regex-processing may become handy too:
$string = preg_replace_callback('/\\\\([0-7]{1,3})/', 'convertOctalToCharacter', $string);
Credits go to http://www.matthewratzloff.com/ blog post

single quote within double quote

i read string documentation on PHP and found out that Single quoted strings will display things almost completely "as it is." Variables and most escape sequences will not be interpreted except \' and \\
I wanted to display a hyperlink whose address should be http://localhost/kk/insert.php/?id="4"
i tried the following code
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=".$id."'>edit</a>";
But it's displaying http://localhost/kk/insert.php/?id=4 (there are no double quotes surrounding 4)
However, i accomplished the result by using
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
My question is that single quotes does interpret \" escape character. So why the first code is not displaying double quotes (that are placed inside single quotes). What am i missing?
You shouldn't have quotes around the integer. Your url should be
http://localhost/kk/insert.php/?id=4
which is accomplished using the following code:
$id = 4;
echo 'edit';
You're dealing with TWO languages there. PHP is doing the echo, and the " quotes are parsed/removed by PHP. Then there's the ' quotes, which are used in the HTML to delimit the href attribute.
With your escaped second version:
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
^--php ^--html ^^--escaped for PHP
Normally that " before $display_result would TERMINATE the PHP string you've been echoing. But since it's been escaped (\"), the escape tells PHP to treat that quote as plaintext, and NOT as a quote. So the PHP string continues, and when this code actually executes and is output from your server, the browser will actually see:
<a href='http://localhost/kk/insert.php/?id="XXX"'>edit</a>
The interpretting difference between single quote and double quote you found is this:
$a = 4;
echo '$a' . "$a"; // $a4
// '$a' just prints `$a`
// "$a" prints `4`, it's interpretted
// alternatively "\$a" prints `$a`
As for the escaping. If your string delimiter is a single quote then you don't need to escape double quotes, and vice versa.
$a = "don't";
// vs
$a = 'don\'t';
$a = '"quote"';
// vs
$a = "\"quote\"";
To do it with your first example, just do :
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=\"".$id."\"'>edit</a>";

Strip " from outside $var

$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.

How do I escape only single quotes?

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("'", "&apos;", $x);
$x = str_ireplace("\\", "&bsol;", $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!

Using preg_replace to back reference array key and replace with a value

I have a string like this:
http://mysite.com/script.php?fruit=apple
And I have an associative array like this:
$fruitArray["apple"] = "green";
$fruitArray ["banana"] = "yellow";
I am trying to use preg_replace on the string, using the key in the array to back reference apple and replace it with green, like this:
$string = preg_replace('|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|', 'http://mysite.com/'.$fruitArray[$1].'/', $string);
The process should return
http://mysite.com/green/
Obviously this isn’t working for me; how can I manipulate $fruitArray[$1] in the preg_replace statement so that the PHP is recognised, back referenced, and replaced with green?
Thanks!
You need to use the /e eval flag, or if you can spare a few lines preg_replace_callback.
$string = preg_replace(
'|http://mysite.com/script.php\?fruit=([a-zA-Z0-9_-]*)|e',
' "http://mysite.com/" . $fruitArray["$1"] ',
$string
);
Notice how the whole URL concatenation expression is enclosed in single quotes. It will be interpreted as PHP expression later, the spaces will vanish and the static URL string will be concatenated with whatever is in the fruitArray.

Categories