doniyor
doniyor

Reputation: 37846

php - search for string in string and replace that

i am asking the question which can be answered by a small attempt in googling but i am not finding anything which can do this, so i am asking here. pls dont downvote and close it, it can be useful for others also:

my problem is: i need to look for some portion of string, and find that and replace that. but my problem is that that portion of string is changing everytime, so i need to inject some regexp.

$url = "www.google.com/test=2";
replace the 'test=2' with 'test=1'
$result = "www.google.com/test=1"

the thing is: the slug can have any number between 1 - 20: test=\d{1,20} this is the case. i tried preg_replace, substr_replace but none of them can do this.

Upvotes: 0

Views: 91

Answers (4)

Matosha
Matosha

Reputation: 116

$url = "website.com/test=1/asdasd/....";
$check= "test=1";
$newval = "test=2"

if(strstr($url,$check))
  $result = preg_replace($check, $newval, $url);

if the value is contained inside the string, then it can be replaced.

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39522

I don't see what's wrong with the following /test=\d+/? I think your problem is that you're forgetting the modifiers (in your example: http://codepad.org/ZZNNr1bH, but you have to use modifiers like so: http://codepad.org/9TEkPYJo)

<?php
    $url = "www.google.com/test=2";
    $result = preg_replace("/test=\d+/", "test=1", $url);
    //                      ^        ^
    var_dump($result);
?>

Update:

That said, like Ashley mentioned, \d{1,20} doesn't mean "one to twenty" but rather "any digit character repeated 1 to 20 times".

If you only want digits from 0-20, use the following regex:

/test=([0-9]|1[0-9]|20)/

Basically meaning (a number from 0-9 OR the number 1 FOLLOWED by any number between 0-9 OR the number 20)

It could also be shortened to

/test=(1?\d|20)/

Meaning (1 repeated 1 or 0 times followed by a digit from 0-9 OR the number 20)

Upvotes: 4

Rajat Garg
Rajat Garg

Reputation: 355

$url = "www.google.com/test=2";
$replacement = 1;
echo preg_replace('/(.*test)=([1-20])/', "$1=1" ,$url);

If I understand the question correctly, this should do.

Upvotes: 1

Ashley Sheridan
Ashley Sheridan

Reputation: 526

Also, \d{1,20} won't match the numbers between 1 and 20, but 0 and 99,999,999,999,999,999,999 which is not exactly what I think you're after.

Upvotes: 1

Related Questions