Forum Moderators: coopster

Message Too Old, No Replies

Removing spam portion of text from string in PHP

         

tonto

11:51 am on May 10, 2009 (gmt 0)

10+ Year Member



Folks,

I have created an HTML form which uses PHP to send an email with the form's data in it. Unfortunately spam bots are populating textbox data in the HTML form with "mailto:" and "http://". So when reading the PHP sent email I see something like "mailto:emailaddress@somewhere.com" and "http://www.somewhere.com". I would like to just remove the "mailto:" and "http://" portions in a string, if present, so that users don't accidentally click on either the "mailto:" and/or "http://" link(s) i.e. just becomes ordinary text instead links. The removed portion could be just "". Incidentally the "mailto:" and/or "http://" could be anywhere in the string. Is there an easy way to do this in PHP? strip_tags, while good, only seems to remove HTML tags but not "mailto:" nor "http://". Please advise.

Thanks and Regards.

PokeTech

10:05 pm on May 10, 2009 (gmt 0)

10+ Year Member



$parse_text = "http://yoursite.com";

$old = array(
"http://",
"mailto:",
);
$new = array(
"",
""
);

$new_text = preg_replace($old,$new,$parse_text);
echo $new_text;

That should work, just change the variables around to your liking.

tonto

10:50 pm on May 10, 2009 (gmt 0)

10+ Year Member



Thanks, greatly appreciated. Just one more question please.

Is it possible to wrap the $new_text line in strip_tags along the lines of:

$new_text .= strip_tags("preg_replace($old,$new,$parse_text)");

I guess the way I have written it above wouldn't work but that's the sort of thing which would do both things.

rob7591

11:10 pm on May 10, 2009 (gmt 0)

10+ Year Member



PokeTech's solution is good, but there's no point in firing up the RegExp engine if you don't have to. Also, you don't have to create a replace array. You can do like this:

$parse_text = "yadda yadda";
$r = array("http://", "mailto:");
$new_text = str_replace($r, '', $parse_text);
echo strip_tags($new_text);

tonto

11:19 pm on May 10, 2009 (gmt 0)

10+ Year Member



Thanks, like that but can I wrap strip_tags around it though along the lines of:

strip_tags($new_text = str_replace($r, '', $parse_text));

rob7591

12:42 am on May 11, 2009 (gmt 0)

10+ Year Member



you can do $new_text = strip_tags(str_replace(...));

if you want to echo it, you can do

echo strip_tags(str_replace(...));

tonto

12:50 am on May 11, 2009 (gmt 0)

10+ Year Member



Thanks everyone. I've implemented this and it works a treat, fantastic. Thanks again.