Is there a way I can check if a user enters a <p> tag inside a form using PHP?
If you simply want to strip all markup use:
strip_tags ( string $str [, string $allowable_tags ] )
otherwise:
substr_replace ( $string , string $replacement , int $start [, int $length ] )
Depends on why you what to know
1 - PHP.net
If it is posted, you can do something like strstr of '<p>' or one of the similar functions, which will then return the location if it exists or NULL if it doesn't.
<?php if ( strstr ( $body, '<p>' ) == NULL )
echo 'All Clear';
else die ( 'Contains <p>' );
if(empty($_POST['foo'])) {
print "Foo empty";
} else {
if(stristr($_POST['foo'], '<p>')) {
print "Contains P tag";
} else {
print "No P tag";
}
}
You could use javascript or jquery .onFocus event.
Assuming they don't enter anything fancy like <p class="stuff">, you can use a simple strpos() call:
$text = $_POST['name_of_field'];
if (strpos($text, '<p>') !== FALSE) {
die("No <p> tags allowed");
}
If they enter attributes, then you'd most likely need a regex, which has its own basket of problems:
$text = $_POST['name_of_field'];
if (preg_match('/<p.*?>/i', $text)) {
die("No <p> tags allowed");
}
Is this what you mean? Assuming you have the form content in a string variable, something like this should work:
<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL | E_STRICT);
$string1 = 'Hello <p> world';
$string2 = 'Hello world';
$foundIt1 = strripos($string1, '<p>');
$foundIt2 = strripos($string2, '<p>');
if (false === $foundIt1) {
echo '1. didn\'t find it';
} else {
echo "1. found it at offset $foundIt1";
}
echo "\n";
if (false === $foundIt2) {
echo '2. didn\'t find it';
} else {
echo "2. found it at offset $foundIt2";
}
?>
If you want to replace or remove them:
$new_data = preg_replace("/<p>/", "whatever you want to replace it with here", $_POST['form_field_id_here']);
If you just want to check for them
strpos("<p>", $_POST['form_field_id_here']);
Then read this to make sure you aren't leaving your site open to attackers:
What's the best method for sanitizing user input with PHP?
(Edit: I know, I know. No regex for HTML parsing. IMHO, if all you are doing is checking for tags then a little bit of regex is better than using a huge HTML parser. That said, if you are checking for many tags and things like <p class="something"> then you should look at this: http://docs.php.net/manual/en/domdocument.loadhtml.php )
Related
Say I have string such as below:
"b<a=2<sup>2</sup>"
Actually its a formula. I need to display this formula on webpage but after b string is hiding because its considered as broken anchor tag. I tried with htmlspecialchars method but it returns complete string as plain text. I am trying with some regex but I can get only text between some tags.
UPDATE:
This seems to work with this formula:
"(c<a) = (b<a) = 2<sup>2</sup>"
And even with this formula:
"b<a=2<sup>2</sup>"
HERE'S THE MAGIC:
<?php
$_string = "b<a=2<sup>2</sup>";
$string = "(c<a) = (b<a) = 2<sup>2</sup>";
$open_sup = strpos($string,"<sup>");
$close_sup = strpos($string,"</sup>");
$chars_array = str_split($string);
foreach($chars_array as $index => $char)
{
if($index != $open_sup && $index != $close_sup)
{
if($char == "<")
{
echo "<";
}
else{
echo $char;
}
}
else{
echo $char;
}
}
OLD SOLUTION (DOESN'T WORK)
Maybe this can help:
I've tried to backslash chars, but it doesn't work as expected.
Then i've tried this one:
<?php
$string = "b<a=2<sup>2</sup>";
echo $string;
?>
Using < html entity it seems to work if i understood your problem...
Let me know
Probably you can give spaces such as :
b < a = 2<sup>2</sup>
It does not disappear the tag and looks much more understanding....
You could try this regex approach, which should skip elements.
$regex = '/<(.*?)\h*.*>.+<\/\1>(*SKIP)(*FAIL)|(<|>)/';
$string = 'b<a=2<sup>2</sup>';
$string = preg_replace_callback($regex, function($match) {
return htmlentities($match[2]);
}, $string);
echo $string;
Output:
b<a=2<sup>2</sup>
PHP Demo: https://eval.in/507605
Regex101: https://regex101.com/r/kD0iM0/1
I am trying to identify a blank lines in a string. Below is my attempt in PHP:
<?php
$alldevs = $_POST['devs'];
$devices = explode("\n", $alldevs);
foreach($devices as $device) {
if(!empty($device)){
echo $device;
} else {
echo "end of value";
}
}
?>
When I input the following:
1
2
3
4
I get this output:
1
2
3
4
But what it should be outputting is this:
1
2
3
end of value
end of value
4
What am I doing wrong?
They probably contain a \r (which is posted on new lines in text areas for some browsers/OS'es), a space or a tab character. You can get rid of these by using the trim() command:
<?php
$alldevs = $_POST['devs'];
$devices = explode("\n", $alldevs);
foreach ($devices as $device) {
$device = trim($device); //Trim that string!
if(!empty($device))
{
echo $device;
}
else
{
echo "end of value";
}
}
?>
Oh, and PLEASE indent your code for your own and everybody elses sake.
Alternatively, split up your string by using regex:
$devices = preg_split("/(\r\n|\n\r|\r|\n)/", $alldevs);
This should give you what you want:
if( trim($device) !== '' )
{
echo $device."<br>";
}
else
{
echo "end of value"."<br>";
}
Outputs:
1
2
3
end of value
4
I think your problem is with \r\n
Use this code
$alldevs = str_replace("\r", '', $alldevs);
Then explode it, and also use trim for clean spaces
$alldevs = trim($alldevs);
first, please read dealing with line endings and wikipedia newline
second, you are using string explode when you should use a function like preg_match_all
code should look something like this (mind the bad regex please):
<?php
$string = $_POST['devs'];
preg_match_all('%^([^\n\r]*)[\n\r]?$%im', $string, $matches);
foreach ($matches[1] as $match) {
if($match) {
var_dump($match);
} else {
echo 'empty line' . PHP_EOL;
}
}
adjust this code to fit your needs, i left a var_dump there so you could see the string length.
Add a check for a string with more than 0 characters,
if(!empty($device) && strlen($device)>0) {
I would also try a use case with \r\n on your line-breaks, you'll run into that as well.
you can try this
$devices = preg_replace('/^\s*$/','end of value',explode("\n",$alldevs));
foreach($devices as $device) {
echo $device, "\n";
}
I am trying to search through a URL for a matching string, but the below code snippet doesn't seem to work.
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file = file($url);
if (in_array($search,$file)) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
If you are just searching for an occurrence of a string on the page, you can use
$str = file_get_contents($url);
if (strpos($str, $search) !== false) {
echo 'Success!';
} else {
echo 'Fail';
}
in_array() checks if an array member is equal to your needle.
It is improbable many websites will have a line which is equal to a only.
Also, is allow_url_fopen enabled?
That code will only find a line that has the exact $search string (likely including whitespace). If you're parsing HTML, check PHP's DOMDocument classes. Or, you can use a regex to pull what you need.
As #alex says, check is allow_url_fopen is enabled.
Also you can use strpos to search the string:
<?php
$url = "http://www.drudgereport.com";
$search = "a";
$file_content = file_get_contents($url);
if (strpos($file_content, $search) !== false) {
echo "Success!";
} else {
echo "Can't find word.";
}
?>
This is my code, it will echo "Not working"
$f = file_get_contents("http://www.google.com");
$text = htmlspecialchars( $f );
$matches = array();
preg_match('#<a.*?</a>#s', $text, $matches);
if ($matches) {
$text2 = $matches[0];
echo $text2;
}
else {
echo "Not working";
}
If I made a variable:
$text = 'Google is your best friend!';
This will work somehow, but it wont when I take it from the:
$text = htmlspecialchars( $f );
Anyone knows why?
This is because htmlspecialchars translates all special characters <&>"', etc into html entities (e.g., & becomes &). Thus your match fails.
htmlspecialchars will convert from
<
to
<
etc.
See the manual.
I've wanted to check if a number in PHP was proper binary. So far I've added this to check if it is devisable by 8:
if(strlen($binary) % 8 == 0){
return true;
} else {
return false;
}
It works, but it obviously allows other numbers to be placed in, such as 22229999.
What method can I use to make sure only 1's and 0's are in the string? such as 10001001. Not sure how to go about this.
This may be faster than firing up the regex engine:
if (strspn ( $subject , '01') == strlen($subject)) {
echo 'It\'s binary!';
} else {
echo 'Not binary!';
}
If you just look for simple characters or want to count them, regex is often quite slow while one or two built in string function can do the job much faster.
Maybe this does apply here, maybe not.
After hearing some remarks in the comments, that this might not work, here's a test case:
<?php
$strings = array('10001001', '22229999', '40004000');
foreach ( $strings as $string )
{
if ( strspn( $string, '01') == strlen( $string ) ) {
echo $string . ' is binary!' . "\n";
} else {
echo $string . ' is NOT binary!' . "\n";
}
}
It does the job.
for variety
if (!preg_match('/[^01]/', $str))
{
echo 'is binary';
}
if (preg_match('~^[01]+$~', $str))
{
echo 'is binary';
}
Inspired by Techpriester's answer (fixed bug):
if (in_array(count_chars($str, 3), array('0', '1', '01'))
{
echo 'is binary';
}
if ( preg_match('#^[01]+$#', $string) )