Joe
Joe

Reputation: 57

how to add special character after few numbers in php

i have a small issue I want to add special character after every 9 numbers. here is example

$new = "111222333444555666777888999";

now i want result something like this

$add_charcter = ($new, "//any method to add special character");

and result shouldbe like this

111222333-444555666-777888999

Upvotes: 0

Views: 404

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The shortest one with preg_replace function:

$new = "111222333444555666777888999";
$result = preg_replace('/.{9}(?!$)/', '$0-', $new);

print_r($result);

The output:

111222333-444555666-777888999

Regexp pattern elucidation:

  • .{9} - match 9 characters

  • (?!$) - negative lookahead assertion, ensures that matched 9-character sequence is not the last one to avoid adding special character at the end of the string

Upvotes: 3

Farsheel
Farsheel

Reputation: 610

chunk_split() Can be used to split a string into smaller chunks.

 $new = "111222333444555666777888999";
 $result = chunk_split($new, 9, '-');
 echo rtrim($result,'-');

Upvotes: 2

Gordon
Gordon

Reputation: 316969

Can use str_split and implode

  • str_split — Convert a string to an array
  • implode — Join array elements with a string

Example:

$str = "111111111222222222333333333";
echo implode("-", str_split($str, 9)); // 111111111-222222222-333333333

Upvotes: 3

Related Questions