1

There is a string variable containing number data , say $x = "OP/99/DIR"; . The position of the number data may change at any circumstance by user desire by modifying it inside the application , and the slash bar may be changed by any other character ; but the number data is mandatory. How to replace the number data to a different number ? example OP/99/DIR is changed to OP/100/DIR.

4 Answers 4

2
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);

print $string;

Output:

OP/100/DIR 
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming the number only occurs once:

$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);

To change the first occurance only:

$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);

Comments

2

Using regex and preg_replace

$x="OP/99/DIR";
$new = 100;
$x=preg_replace('/\d+/e','$new',$x);

print $x;

2 Comments

it's quite the same as alexey's answer , so what's difference between using ! ?
I used e modifier so that you can execute anything in the second parameter. Regarding !, there is no difference actually. Its just a delimiter. Check php.net/manual/en/regexp.reference.delimiters.php .
1

The most flexible solution is to use preg_replace_callback() so you can do whatever you want with the matches. This matches a single number in the string and then replaces it for the number plus one.

root@xxx:~# more test.php
<?php
function callback($matches) {
  //If there's another match, do something, if invalid
  return $matches[0] + 1;
}

$d[] = "OP/9/DIR";
$d[] = "9\$OP\$DIR";
$d[] = "DIR%OP%9";
$d[] = "OP/9321/DIR";
$d[] = "9321\$OP\$DIR";
$d[] = "DIR%OP%9321";

//Change regexp to use the proper separator if needed
$d2 = preg_replace_callback("(\d+)","callback",$d);

print_r($d2);
?>
root@xxx:~# php test.php
Array
(
    [0] => OP/10/DIR
    [1] => 10$OP$DIR
    [2] => DIR%OP%10
    [3] => OP/9322/DIR
    [4] => 9322$OP$DIR
    [5] => DIR%OP%9322
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.