[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](img/ogp.png)
When entering a title in WordPress

Copying like this in Word

When you paste it into WordPress and save it

...Hmm?

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

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...

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.




If this was helpful, we appreciate your support!
Any support received will be used for childcare.
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