Is there a way I can check if a user enters a <p> tag inside a form using PHP?
7 Answers
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
Comments
if(empty($_POST['foo'])) {
print "Foo empty";
} else {
if(stristr($_POST['foo'], '<p>')) {
print "Contains P tag";
} else {
print "No P tag";
}
}
2 Comments
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");
}
Comments
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";
}
?>
Comments
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 )