Home Blog Split a String into Two by Character Length with PHP

Split a String into Two by Character Length with PHP


If you’re in the business of printing URLs to a screen, you’ll often have a need to split the string into two separated by a string of three dots (…). The link title tag is often used to show the entire URL. There are two functions on this page (formerly published on Internoetics) that accomplish the same thing; the first is easier to use.

The function will take a long string (say, something like http://www.beliefmedia.com/some-directory/another-directory/this-is-a-long-string-we-want-to-truncate) and return a split string: http://www.beliefmedia.com/som...nt-to-truncate. While I’ve used a URL for the example, any string can be used.


The first function utilises PHP’s substr-replace function.

The output of the above code would be The Quick Brown…er the Lazy Dog (bolding is mine). Note that the $maxcharacters doesn’t include the 3 dots (or whatever separator you might replace it with). In our case, replacing the centre of the string with three dots means the total string length will be 33 characters.


The second function uses a preg_replace_callback() to truncate a URL into a split URL link.

The function will split the the portion of the URL string that comes after the root domain name (the domain name is preserved).


Title: Split a String into Two with PHP
Description: Split a String (or URL) into two by character length with PHP. Includes two functions.
Download: PHP Code (V0.2) | Plugin Page

Shortt URL for this post: http://shor.tt/2nOx


Please enter your comment!
Please enter your name here