0

I have a text string that is set in a variable to a value like these:

$str = 'type=showall'

or

$str = 'type=showall&skip=20'
$str = 'type=showall&skip=40'
$str = 'type=showall&skip=60'

and so on.

I need to check to see if there is a "skip" value present in the string, and if so replace it with a new number that is stored in a $newSkip variable and keep the string the same except for the change to the skip value.

For example if the string was:

$str = 'type=showall&skip=20'

and

$newSkip = 40

then I would like this to be returned:

$str = 'type=showall&skip=40'

If there was no skip value:

$str = 'type=showall'

and

$newSkip = 20

then I would like this to be returned:

$str = 'type=showall&skip=20'

I'm fairly new to PHP so still finding my way with the various functions and not sure which one/s are the best ones to use in this scenario when the text/value you're looking for may/may not be in the string.

4

1 に答える 1

3

PHPには、お持ちparse_str()の文字列に似た文字列を受け取り、キーと値のペアを持つ配列を返すという便利な関数があります。その後、特定の値を調べて、必要な変更を加えることができます。

$str = 'type=showall&skip=20';

// this will parse the string and place the key/value pairs into $arr
parse_str($str,$arr);

// check if specific key exists
if (isset($arr['skip'])){
    //if you need to know if it was there you can do stuff here
}

//set the newSkip value regardless
$arr['skip'] = $newSkip;

echo http_build_query($arr);

このhttp_build_query関数は、配列を最初に使用したのと同じURI形式に戻します。この関数は最終的な文字列もエンコードするため、デコードされたバージョンを確認する場合は、を介して送信する必要がありますurldecode()

参考文献-

于 2012-09-17T16:23:28.920 に答える