Encode specific characters within tag attributes - php

Using PHP, I would like to encode specific characters (the > and < characters) within the attribute values for any tag.
For example, <input type="text" data-name="Oliver<>Nassar"> would become <input type="text" data-name="Oliver<>Nassar">.
I'm not picky regarding the attribute name (eg. data-name or value attribute names). While I am happy to presume a whitespace character (\s) before the attribute value (eg. <input data-name="...">) it would be great if that were not a condition, such that I could meet cases such as <input type="text"data-name="Oliver<>Nassar">
I imagine PHPs preg_replace_callback will be made use of, but as far the actual expression, I could use some help there.

Here is the expression I came up with:
'/' .
'(' .
'\s{1}' .
'[a-z\-]+' .
'\s?' .
'=' .
'\s?' .
'(' .
'[\'|"]{1}' .
')' .
')' .
'([^\2]*)' .
'\2' .
'/iU',
Hope this is helpful to someone else.

Related

php string concatenation "A<"."B" does not work

I'm writing a function to output HTML elements, the problem is: when I try to concatenate this two strings:
$tag = "<" . "tag";
The instruction echo $tag outputs nothing. What is wrong
As mentioned in comments, special characters like <, will be parsed by browser as HTML, therefore you won't see them as you expect.
Its almost the same thing:
$tag = 'p';
echo '<' . $tag '>' . Test . '</' . $tag . '>';
Which is the same as
echo '<p>' . Test . '</p>';
So after script execution you'll see just
Test
in a browser. but when viewing a source, it will be as
<p>Test</p>
If for some reason you want to see HTML tags, then you need to escape special chars using built-in function htmlentities().
In your case, you can just prepare a string, then just echo it like
echo htmlentities($string);
If by tag you mean an HTML entity then its not going to be seen in the browser. You may need to do a 'view source' to see what was created by echo call.

PHP echo integer value within div tag

echo "<td>".$value["rating"]."<div class=ratingOutput data-average=".$rates." **data-id="$value["id"]"**></div>".$newline.$rateHere.$starOutput."</td>";
I want data-id to be and integer value, but cannot set it to any int for example even if i change the above code to this
echo "<td>".$value["rating"]."<div class=ratingOutput data-average=".$rates." **data-id="4"**></div>".$newline.$rateHere.$starOutput."</td>";
I get an error as such:
syntax error, unexpected '$value' (T_VARIABLE), expecting ',' or ';'
You're having an error concatenating of your string.
echo "<td>".$value["rating"]."<div class=ratingOutput data-average=".$rates." **data-id=". 4 . "**></div>".$newline.$rateHere.$starOutput."</td>";
Change this:
echo "<td>".$value["rating"]."<div class=ratingOutput data-average=".$rates." **data-id="4"**></div>".$newline.$rateHere.$starOutput."</td>";
To this:
echo '<td>'.$value['rating'].'<div class="ratingOutput" data-average="' . $rates . '" data-id="' . $value['id'] . '"></div>'.$newline.$rateHere.$starOutput.'</td>';
The best way when working with html in PHP is to use single quotes because normally you will be using double quotes for your attribute, by then you will need to escape the double quote. for the attributes you will be using.
Whenever I build HTML in PHP code, I use the heredoc syntax:
echo <<< EOT
<td>
{$value['rating']}
<div class="ratingOutput" data-average="$rates" data-id="4"></div>
$newline
$rateHere
$starOutput
</td>
EOT;
...something like that.
So you don't have to worry about escaping your double-quotes or concatenation. You can format your HTML so that it's easier to read (perhaps you don't need that $newline variable, if it's just a newline character, I can't tell).
(It doesn't have to be used with echo either, you can use it in variable assignment $html = <<< EOT - no whitespace after your token or it will fail!
If you need the last new-line character in your variable then you need a blank line before your closing token, because the closing character sequence is actually \nEOT;\n.
Many examples in articles use EOT as the token, but I abandoned that for _ a long time ago, shorter.

Escaping minus sign in PHP echo statement

I'm sure I'm missing something obvious here: the following is echoing lat-long variables from MySQL, and the longitude variable begins with a minus sign, which prevents the echo statement from reading it and all that follows it. I'm sure there is a way to clean/escape that but just can't work it out.
echo "http://maps.google.com/maps?ll=" . $row['latitude'] . "," . $row['longitude'] . " target=_new>View in Google Maps";
This is output from a PDO query and testing passing the lat-long into Google Maps.
As I understand, it's a link?
Then, use urlencode for string.
The minus signs are not a problem. You may need to urlencode() because of the comma, but you need quotes around the URL in the href as well:
echo '<br /><a href="http://maps.google.com/maps?ll='
. urlencode($row['latitude'] . ',' . $row['longitude'])
. '" target="_new">View in Google Maps</a>';

Escape sequence for a space character in PHP

Currently I'm using the below snippet, which indent the resulting HTML by using several space characters:
add_filter('get_search_form', 'filter_search_form');
function filter_search_form($form) {
$form = ' <form role="search" method="get" id="searchform" action="' . home_url('/') . '"><input type="text" placeholder="' . __('Search') . '" value="' . get_search_query() . '" name="s" id="s"><input type="submit" id="searchsubmit" value="' . esc_attr__('Search') . '"></form>' . "\n";
return $form;
}
Now I've been reading some about whitespace characters (\t for tab, \n for newline, etc.), but I'm not entirely sure how to implement this in this situation.
I've tried using \s for a single space, but without any luck thusfar.
Being relatively new to PHP, I hope you could assist (preferably without using a 'regular' space character).
According to http://php.net/manual/en/regexp.reference.escape.php, the general hexadecimal escape sequence \x20 should work, as should \040 (octal).
Personally, though, I don't see much (if any) benefit to ever specifying spaces in this manner, as it would make your code less readable, IMHO. Just stick literal spaces inside your single- or double-quotes (like you have now) and be done with it.
Alternatively, if you're trying to use whitespace to indent the resulting HTML code (as it seems you are), doing so in units of \t isn't the end of the world.
Characters like \t and \n need to be in double quotes...
$string = "\t" . '<form></form>';
If you want to insert a tab before it you could use:
$string = "\t" . '<form>....';
(don't forget the double quotes, the single ones don't work with \t, \n and friends!)
If you want spaces, just use spaces!
$string = " " . '<form>....';
It's html code, so they will be present in the source code of your page. They won't ‘collapsed’ into a single space.

is there a function to add forward slashes before " inverted commas in a string

I am using PHP, i want to display a string which comes as title of a post, in a textbox as value. if this title has inverted commas then the string value tag of input field terminates on that quote. now as there is an add slash function to add back slashes, is there a similar function to add forward slashes ? but just before quotes, and not any other character
Use the htmlspecialchars function to encode the string within the value="..." attribute.
Example:
$sometext = 'Hello "world"!';
echo '<input type="text" value="' . htmlspecialchars($sometext) . '" />';
// outputs <input type="text" value="Hello "world"!" />
As I understand, you are trying to put some text into an HTML <input type="text /> ?
If yes, you'll need to use the htmlspecialchars function ; for instance :
echo '<input type="text" name="my_element" value="'
. htmlspecialchars($value, ENT_COMPAT, 'UTF'8)
. '" />';
Note that you have to specify a charset, if you are not working in ISO-8859-1.
With this function (quoting) :
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
You can use preg_replace, but what do you want to achieve with forward slashes?
preg_replace('/\"/', '/\"', $string);

Categories