Customizing SMF > Tips and Tricks

Trim Subject and Message Body

(1/2) > >>

MobileCS:
(SMF 2.0.xx Only)

This code is for users who want to trim any whitespace from either side of the " subject title " and remove any blank lines from the start -and- end of the message body.

Sources\Post.php

Find:

--- Code: --- // Collect all parameters for the creation or modification of a post.
$msgOptions = array(
'id' => empty($_REQUEST['msg']) ? 0 : (int) $_REQUEST['msg'],
'subject' => $_POST['subject'],
'body' => $_POST['message'],
--- End code ---

Replace:


--- Code: --- // Collect all parameters for the creation or modification of a post.
$msgOptions = array(
'id' => empty($_REQUEST['msg']) ? 0 : (int) $_REQUEST['msg'],
'subject' => trim($_POST['subject']),
'body' => preg_replace('/^(\s*<br\s*\/?>\s*)+|(\s*<br\s*\/?>\s*)+$/', '', $_POST['message']),
--- End code ---

This code will trigger when creating new messages and modifying them.

Suki:
Regex should be used as a last resort thing, for this specific case, trim() will do the job just fine unless you somehow allow HTML in the subject too.

If you still want to go with regex, the one you're using will fail with an html5 br tag: <br>

MobileCS:
SMF converts all carriage returns to "<br />" for message text. That is why I am using regex. In which cases would this not happen?

I've modified my code so the regex handles <br>, <br >, <br   >, <br/>, <br />, <br   />.

Suki:
Indeed it does. The reason why I suggested trim() is because catching all variations with regex its complicated, for example, your updated regex will still fail with a text like this one:


--- Code: ---<br> <br > <br   > <br/> <br /> <br   />some text<br> <br />

--- End code ---

It will only remove the first br tag.

MobileCS:
How can trim() be used for $_POST['message']? When I tried, it did nothing.

After checking why things weren't working, I saw that "$_POST['message']" contained actual "<br />" characters - so regex is our only option for the message text.

I've updated my regex so it fixes your issue, and also trims any possible whitespace before or after the <br> tags.

Navigation

[0] Message Index

[#] Next page

Go to full version