Is there a way I can check if a user enters a <p> tag inside a form using PHP?
7 Answers
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>' );
 
    
    - 3,977
- 1
- 25
- 27
if(empty($_POST['foo'])) {
   print "Foo empty";
} else { 
   if(stristr($_POST['foo'], '<p>')) {
      print "Contains P tag";
   } else {
      print "No P tag";
   }
}
 
    
    - 73,447
- 11
- 124
- 153
You could use javascript or jquery .onFocus event.
 
    
    - 5,475
- 13
- 47
- 86
- 
                    
- 
                    ahh I see. I assumed you wanted to know when a control inside thetag was in focus or not. – ItsPronounced Sep 13 '10 at 23:36
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");
}
 
    
    - 356,200
- 43
- 426
- 500
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";
}
?>
 
    
    - 2,348
- 1
- 21
- 26
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 )
 
    
    - 1
- 1
 
    
    - 9,590
- 7
- 38
- 49
 
     
    
and
.
– Paulo Scardine Sep 13 '10 at 23:38