How to remove one instance of one string in PHP?
I have a open source editor on the cms that I am making that automatically inserts a
<br />
tag at 开发者_如何学编程the beginning of the post it submits to the database. This makes validation a pain, since even though there is no real text being submitted, the form still accepts the break tag as input and prevents the "Please enter some text" error from showing.
So I tried to remove the opening break tag by filtering my input like this:
substr($_POST['content'], 6);
This works as long as the user doesn't press the backspace a couple of times which removes the break tag in which case the first 8 characters of the post gets removed even if they are not a break tag.
So how can I remove the first 6 characters of the input ONLY if those first 6 characters are composed of the break tag. Also I don't want to remove all break tags, only the one at the very beginning of the post.
Performant and verbose:
if (substr($_POST['content'], 0, 6) == '<br />') {
$_POST['content'] = substr($_POST['content'], 6);
}
Not so verbose, but slightly slower:
$_POST['content'] = preg_replace('#^<br />#', '', $_POST['content']);
$content = $_POST['content'];
if ( substr($content, 0, 6) == '<br />' )
$content = substr($content, 6);
Creating a workaround for your open source editor is not the solution you should be seeking. Wouldn't it be wiser to just fix the editor so it doesn't insert that <br />
there so you just don't have to worry about it at all?
You can use eg. preg_replace:
$text = preg_replace('#^<br />#', '', $text);
If you don't want to use regexps, you could check with substr before removing:
if (substr($text, 0, 6) == '<br />')
$text = substr($text, 6);
Here's what I think to be a better solution of testing whether the user has actually entered something:
if (!strlen(trim(strip_tags($_POST['content'])))) {
// no content
}
else {
// some content
}
This basically tests if there is anything other than HTML tags in the input.
First remove blank spaces at the beginning with ltrim
, then test if there is a br. If there is a br remove it and do another ltrim
to remove blanks after the br.
$str = ltrim($_POST['content']);
if (substr($str, 0, 6) == '<br />'){
$str = ltrim(substr($str, 6));
}
if ($str){
//some content
} else {
//no content
}
In this way you ignore blank spaces and new lines before and after the br.
精彩评论