开发者

Using str_replace to replace variable character

Basically I am trying to do an str_replace with "?cat=(insert number here)"

$queryString2 = str_replace("cat=(insert n开发者_开发问答umber here)", "cat=4", $queryString);

Is there a way this can be accomplished? Str_replace + one character because the value im searching for could be anything.

?cat=7
?cat=3
?cat=4

Any suggestions?


A more reliable way of handling query strings would be to actually parse them.

// If your original query string was just the data in $_GET, clone $_GET:
$new_query = $_GET;
// Otherwise, parse the original query string using parse_str:
parse_str($original_query_string, $new_query);
// Then, set the new cat value, and build a new query string.
$new_query['cat'] = 4;
$new_query_string = http_build_query($new_query);

The technique you originally describe is the job of a regular expression :)

$queryString2 = preg_replace('/cat=[0-9]+/', 'cat=4', $queryString);

The regular expression cat=[0-9]+ matches the string cat= followed by one or more (+) digits ([0-9]). preg_replace replaces all matches of the regular expression (argument 1) found in the original string (argument 3) with the replacement string (argument 2) and returns the result.

Note that this will also replace dog_and_cat=1 with dog_and_cat=4. borkweb's answer is a more complex regex, but handles that edge case if it could arise (e.g. this is a query string provided by the user).

I prefer the actual query parsing, but the regular expression solution should ideally work just as well, assuming no edge cases.


Yeah, you can use preg_replace:

$queryString2 = preg_replace('/([&?])cat=[0-9]+/', '\1cat=4', $queryString);

That regex will make sure you only grab the "cat" query string. The pieces are as follows:

([&?])  # match either and ampersand or question mark
cat=    # match "cat="
[0-9]+  # match 1 or more digits.

The \1 in the second parameter inserts into the replace string whatever was captured in the parens from the first parameter.

However, using the parse_str example that Matchu gave may be a bit more foolproof with only a little bit of overhead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜