简体   繁体   中英

str_replace with a variable character

I'm wondering if what I need is even possible. I have a string and I want to replace a portion of it by another string nothing hard BUT the string that I want to replace has some 'dynamic' characters.

i have a string that contains:

http://someurl.com/whatever?page= *

where * can be any number

I need to have:

http://someurl.com/whatever?page= *#/somestring

where #/somestring is hardcoded

You can use strpos() to find the start position and end position of the string. Then you just use str_replace to edit the link.

Look at my earlier answer here: PHP To Show Title From Reffering URL In your case you should not use strip_tags, but the rest is quite the same.

This code should do it:

$string="http://someurl.com/whatever?page=129833";
$replacement="#/somestring";
echo preg_replace('/(http:\/\/someurl\.com\/.*?page=[0-9]+)/','\1'.$replacement,$string);

It prints:

http://someurl.com/whatever?page=129833#/somestring

As others suggested you could use a regex for these sort of things; in your case I would suggest something like this:

$sub = 'http://someurl.com/whatever?page=23';
$new = preg_replace('/\?page=([0-9]+)/', '?page=$1#/something', $sub);

echo $sub;
echo '</br>';
echo $new;

It prints:

http://someurl.com/whatever?page=23
http://someurl.com/whatever?page=23#/something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM