In PHP, you can use the regular expression "preg_replace ($pattern, $replacement, $subject, $limit, $count)" to achieve search and replacement.
Recommended: "PHP Video Tutorial"
php regular search and replacement preg_replace
preg_replace — Perform a regular expression search and replacement
Method description:
preg_replace ( $pattern , $replacement , $subject , $limit , $count)
Search for the part of the subject that matches pattern and replace it with replacement.
$limit, $count parameters are optional
limit: The maximum number of substitutions for each pattern on each subject. The default is -1 (unlimited).
count: If specified, will be filled with the number of completed substitutions.
Return value:
If subject is an array, preg_replace() returns an array, otherwise it returns a string.
If a match is found, the replaced subject is returned, otherwise the unchanged subject is returned. If an error occurs, NULL is returned.
Instance 1:
<?php $PIWIK_API = 'filter_offset={offset}&period={period}&date={date}'; $patterns = array( '/{offset}/', '/{period}/', '/{date}/' ); $replacements = array( 33, 'day', '216-11-11' ); $url = preg_replace($patterns, $replacements, $PIWIK_API); //结果: $url = "filter_offset=33&period=day&date=216-11-11"
Instance 2:
<?php $PIWIK_API = array( 'filter_offset' => '{offset}', 'period' => '{period}', 'date' => '{date}' ); $patterns = array( '/{offset}/', '/{period}/', '/{date}/' ); $replacements = array( 33, 'day', '216-11-11' ); $url = preg_replace($patterns, $replacements, $PIWIK_API); //结果: /* $url = array(3) { ["filter_offset"]=> string(2) "33" ["period"]=> string(3) "day" ["date"]=> string(9) "216-11-11" } */
The above is the detailed content of How to implement search and replace in php regular. For more information, please follow other related articles on the PHP Chinese website!