PHP substr vs mb_substr
1 min read

PHP substr vs mb_substr

substr vs mb_substr in printing special characters in Laravel Blade.

Recently, I ran into an issue on my job board Arbeitnow. For a couple of job postings, the HTML title tag was being empty, and that's an issue for users & from SEO perspective.

The title tag is rendered via Blade templates, and the value is passed from the controller.

<html>
<head>
<title> {{ $title }} </title>
</head>
...

When the $title variable is passed, it is cut down to just 70 characters as this is the recommended title length for Google.

$title = substr("Title here", 0, 70);

I started looking at the few job postings that returned an empty string instead of a valid string.

$title = substr("SEO Manager at ZAP-Hosting GmbH & Co. KG | North Rhine-Westphalia | Münster | Germany", 0, 70);

My expectation was that it would return SEO Manager at ZAP-Hosting GmbH & Co. KG | North Rhine-Westphalia | Mü as the result. Unfortunately for me, it didn't. When I dumped the variable, the result was this:

b"SEO Manager at ZAP-Hosting GmbH & Co. KG | North Rhine-Westphalia | MÃ"

Notice the weird b before it? Immediately, I knew this was an issue because the special character ü and therefore needed to be handled differently.

I found two possible solutions and both work well:

  • Adjust the blade template to print as a special character (no output escaping)
<html>
<head>
<title> {!! $title !!} </title>
</head>
...