Front-End & Daily

[PHP] How to fix the issue where Word line break codes like [OBJ] appear in WordPress

[PHP] How to fix the issue where Word line break codes like [OBJ] appear in WordPress

When entering a title in WordPress

Add WordPress Title

Copying like this in Word

Word Copy

When you paste it into WordPress and save it

Add WordPress Title

...Hmm?

Add WordPress Title

What is this?! (Well, I can mostly guess...)

Add WordPress Title

A mark like [OBJ], which seems to be a Word line break code, appeared.
Since this happened, I'd like to introduce a simple solution.

Well, you just need to be careful when copying from Word and do it like this...

Copy from Word without line breaks

Try JSON encoding

For the state where it becomes "Announcement Title" and

"Announcement Title[OBJ]",

I tried JSON encoding each.

$post_title = get_the_title();
var_dump(json_encode($post_title));

The result is

Announcement Title

"\u304a\u77e5\u3089\u305b\u30bf\u30a4\u30c8\u30eb"

Announcement Title[OBJ]

"\u304a\u77e5\u3089\u305b\u30bf\u30a4\u30c8\u30eb\ufffc"

Clearly, "\ufffc" is appended to the end.

Delete if the end matches

I'll try JSON encoding it and deleting it if the end matches "\ufffc".

This is how I'll do it.

If I were to JSON encode and decode everything without question, other problems might arise,

so I'll only JSON encode and decode if it matches the end.

Before

//Get title and remove HTML
$post_title = strip_tags(get_the_title());
//Output
echo '<p>'.$post_title.'</p>';

After

//Get title and remove HTML
$post_title = strip_tags(get_the_title());
//When the end of the json_encoded string matches "\ufffc"
if(preg_match('/\\\ufffc"?\'?$/', json_encode($post_title)) === 1){
	$post_title = preg_replace('/\\\ufffc("?\'?)$/', '$1', json_encode($post_title));
	$post_title = json_decode($post_title);
}
//Output
echo '<p>'.$post_title.'</p>';

If you know a better way!

Or if it didn't work in my environment! Please let me know in the comments.

Comments

After reviewing the content, we will publish it, omitting personal information.

Enter Name and Email Address

Please enter if you would like a reply by email.

Personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and then click "Send".

If this was helpful, we appreciate your support!
Any support received will be used for childcare.

Send support via OFUSE


Alternatively, buy something from the buttons below to show your support
(You don't have to buy the linked product.)

Amazon

Rakuten Ichiba

Yahoo! Shopping

PR

As an Amazon Associate, "Ken" earns income from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark