Jump to content

[SOLVED] nsert character into variable for displaying


Dragen

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)){

Archived

This topic is now archived and is closed to further replies.

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