<?php $keyword="aaaaaaa"; $i++; $keyworda = preg_replace("/a/", "a$i", "$keyword"); echo "$keyworda"; ?> PHP: this is my stupid code. the result is "a1a1a1a1a1a1a1" how to do? get result is "a1a2a3a4a5a6a7" thank you
Assuming your string/keyword doesn't consist only of the letter 'a', then theirs many ways of achieving this. <?php $str = 'aaaaaaa'; $chars = str_split($str); $result = NULL; foreach ($chars as $key => $char) { $result .= $char.($key + 1); } echo $result; PHP: or: <?php $str = 'aaaaaaa'; $chars = str_split($str); $result = NULL; for ($i = 0; $i < strlen($str); $i++) { $result .= $chars[$i] . ($i + 1); } echo $result; PHP: or: <?php $str = 'aaaaaaa'; $result = array_map(function($char) { global $i; ++$i; return $char.$i; }, str_split($str)); echo implode('', $result); PHP:
is possible via preg_replace? also, i'd like to replace anything possbile keywords. like below $keyworda = preg_replace("/<b>(.*)</b>/", "<b>$i</b>", "$keyword"); find all <b>(.*)</b> and replace to be <b>number+1</b> <b>com</b> --> <b>1</b> <b>net</b> --> <b>2</b> <b>org</b> --> <b>3</b>.....etc thanks for help.
This works: $i=0; $keyworda = preg_replace_callback("~<b>(.*?)</b>~", create_function('','global $i; return ++$i;'), $keyword); PHP: $keyword = "<b>a</b>B<b>a</b>C<b>a</b>D<b>a</b><b>a</b><b>a</b><b>a</b>"; Outputs: 1B2C3D4567
If you use create_function within a pattern with more than a couple of matches, it's more efficient to create an actual function and pass that function to preg_replace_callback. preg_replace_callback will invoke create_function and create the anonymous function every time there's a match. For the original example string of "aaaaaaa", the anonymous function would be created 7 times. If this is an article or something where you may have a couple of hundred matches, this can be a problem.