View Full Version : Highlight invalid characters in string

01-10-2004, 06:11 PM
Ok, I've been trying to figure this out for about 6 hours and everything I've tried just hasn't worked the way I want it. This is what I've got so far (had to use code tag as php tag kept stripping the backslashes)

// being called by validate("mem-em/_-e mssssss+em",username,3,12);

function validate($field,$what,$minchar,$maxchar){

$notice = 'Ok, validated fine';
if(strlen($field) < $minchar){
$notice = ucfirst($what).' must contain more than '.$minchar.' characters<br>';
if(strlen($field) > $maxchar){
$notice = ucfirst($what).' must be no more than '.$maxchar.' characters<br>'."\n";
$invalid = array("-","\+","\.","\\\\","\s");

foreach($invalid as $no){

if($no == "\s"){
$no = "spaces";
$errors .= stripslashes($no.' ');
$notice .= 'ERROR: '.ucfirst($what).' must not contain: '.$errors."<br>\n";

return $notice;

I'm wanting it to highlight all instances of $invalid in the $field. I've tried adding str_replace($invalid,"<b>".$invalid."</b>",$field) but that just returns as Array being highlighted. I've also tried str_replace and preg_replace in the foreach loop, but then it lists the $field with all the errors found too. I can't think of any other way to do it.

Any ideas?

01-10-2004, 07:20 PM
Here's a possible solution:

$highlightedField = preg_replace(
'/('.implode($invalid, '+|').')/',
'<span style="color:red;font-weight:bold">\\1</span>',

$notice .= 'ERROR: '.ucfirst($what).' must not contain: '.$errors."<br>\n";
$notice .= 'you wrote: ' . $highlightedField;

Note that I decided to add red color to the invalid chars, because a bold '-' is indistinguishable from normal text.

01-10-2004, 07:25 PM
:D Thanks alot, just what I was after. I knew you'd be the one to rescue me lol