|
Access individual regex matches in a string or file
|
Email
|
| Submitted on: |
11/1/2006 5:58:56 AM |
| By: |
Cesay
|
| Level: |
Intermediate |
| User Rating: |
By 1 Users |
| Compatibility: |
PHP 3.0, PHP 4.0, PHP 5.0 |
| Views: |
7686 |
|
|
|
|
|
This shows how you to loop through an array and access regular expression matches individually, in this case replacing them, and rebuild the new array at the same time. If you're wondering why not just use a replace function, it's because I needed to replace each regular expression match in a file with a different item; replace function would replace them all with the same.
|
| |
Terms of Agreement:
By using this article, you agree to the following terms...
- You may use
this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
- You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.
- You may link to this article from another website, but ONLY if it is not wrapped in a frame.
- You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
|
$tpl_src = implode(file($my_file));//template file with variables
$pattern = "/\[p:(.+)\]/";// the regex pattern to look for and change each individually
$pieces = preg_split($pattern,$tpl_src, -1, PREG_SPLIT_DELIM_CAPTURE);//split the data according to the regex pattern
/*
I was using an older version of php that doesn't have array
referencing yet so the var $new_src is used to copy the
array and change the parts I want. If you have php5,
array referencing would be a better way to do this.
*/
$new_src = ''; //This will hold the new data.
foreach($pieces as $value){//loop through the array
if(is_a_variable($value){//My function to determine whether the regex pattern was a valid variable, you can lose this check and it'll work fine.
$value = "[new value " .rand(1,100). "]";//Replace each individual variable with something different and unique to each variable.
}
$new_src .= $value;//Pieces the array back together bit by bit.
}
echo stripslashes($new_src); //Display the new page with each of the same variable now showing a different value.
|
|
Other 1 submission(s) by this author
|
|
Report Bad Submission
|
Your Vote
|
| |
Other User Comments
|
There are no comments on this submission. |
Add Your Feedback
Your feedback will be posted below and an email sent to
the author. Please remember that the author was kind enough to
share this with you, so any criticisms must be stated politely, or they
will be deleted. (For feedback not related to this particular article, please
click here instead.)
To post feedback, first please login.
|