Jump to content

Recommended Posts

Is there a way of splitting a variable after a certain length, adding a character, then continue writing the rest of the variable?

Basically I have a set of number that I'm getting from a database, but I want to insert a space in the middle..

for example:

01234567 //would become
0123 4567

 

I'm wanting to do this for displaying the numbers as the numbers are stored without the spaces. This is done for a reason, not to make it a pain for myself.

<?php
function split($string, $chr = " ") { //.chr is the character you want to add, not necessary there's a space added automatically
$c = strlen($string);
$m = ceil($c / 2);
$a = substr($string, 0, $m);
$b = substr($string, $m, $c); // i'm guessing $b = substr($string, $m); would be enough
$string = $a.$chr.$b;

return $string;
}
?>

 

something like that should do the trick

Hey, thanks for the help!

I've actually found a way of setting the values into the database with the space in now, so I don't need to add the space when I display it...

 

The reason was I'm using regex() to check the input before adding it into the database. Checking that it was all numbers, but I couldn't figure out how to do it so it was numbers with a space in it, so I thought it'd be easier to add the space after for displaypurposes.

Here's my regex() if you're interested:

if(!ereg('^[0-9]{11}|[0-9]{5}[[:space:]][0-9]{6}$', $value)){

That gives two options. A list of numbers 11 characters long or a list of 5 numbers a space, then 6 more numbers.

 

 

EDIT: here's my updated regex() as I noticed an error in the previous one:

if(!ereg('^([0-9]{11}|[0-9]{5}[[:space:]][0-9]{6})$', $value)){

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.