0

Is there a way I can check if a user enters a <p> tag inside a form using PHP?

cssNUT
  • 41
  • 1

7 Answers7

1

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>' );
judda
  • 3,977
  • 1
  • 25
  • 27
1
if(empty($_POST['foo'])) {
   print "Foo empty";
} else { 
   if(stristr($_POST['foo'], '<p>')) {
      print "Contains P tag";
   } else {
      print "No P tag";
   }
}
Paulo Scardine
  • 73,447
  • 11
  • 124
  • 153
1

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

taylorjes
  • 434
  • 3
  • 18
0

You could use javascript or jquery .onFocus event.

ItsPronounced
  • 5,475
  • 13
  • 47
  • 86
0

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");
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

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";
}


?>
mr. w
  • 2,348
  • 1
  • 21
  • 26
0

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 )

Community
  • 1
  • 1
Computerish
  • 9,590
  • 7
  • 38
  • 49