how to i replace
Apple 123456
to
Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6
by php pcre?
how to i replace
Apple 123456
to
Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6
by php pcre?
With this one you get partially what you want:
<?php
echo preg_replace('/([0-9])/', 'Apple $1|', 'Apple 123456');
That results in: Apple Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6|
For removing the first "Apple" you could str_replace()
or explode()
the initial string, resulting something like
<?php
$string = 'Apple 123456';
$string = str_replace("Apple", "", $string);
echo preg_replace('/([0-9])/', 'Apple $1|', $string);
The result here is Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6|
.
You can remove the last pipe by using substr($result, 0, -1)
.
The final code will look like this:
<?php
$string = 'Apple 123456';
$string = str_replace("Apple", "", $string);
$regex = preg_replace('/([0-9])/', 'Apple $1|', $string);
echo substr($regex, 0, -1);
Modified version of Bogdan's regex using negative lookahead.
Replace number with "number|Apple "
unless it is the last character in the string.
<?
$string = "Apple 123456";
echo preg_replace('/([0-9])(?!$)/', '$1|Apple ', $string);
?>
Ouput: Apple 1|Apple 2|Apple 3|Apple 4|Apple 5|Apple 6