Add character in the middle of a string

I have a list of six digit codes (some are 7). What I need is to put a space after the fourth character of each code, to make it more readable in my views. It would be like:

234201
234202
234203

to

2342 01
2342 02
2342 03

Is there any way to do this quickly in cake php? Other than doing all the work with tail and other functions that would require some more coding.

Answers


Use PHP's substr_replace:

substr_replace('123456', ' ', 4, 0); // returns '1234 56'

It's probably a more elegant solution to this, but at least it works.

Just appends a space in between to parts of the string.

$string           = "123456";
$formatted_string = substr($string, 0, 4) . " " . substr($string, 4);

$formatted_string should now be 1234 56


Need Your Help

How to mock request object for rspec helper tests?

ruby-on-rails ruby-on-rails-3 rspec rspec2 view-helpers

I've a view helper method which generates a url by looking at request.domain and request.port_string.

Dynamically change filter value without Property Page

directshow directshow.net

I just wrote a simple DirectShow Filter (which inherits from CTransformFilter).