Jump to content


Photo

regex help, preg_replace


  • Please log in to reply
2 replies to this topic

#1 mapunk

mapunk
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 21 August 2006 - 08:02 PM

I've tried working on this for a pretty long time, but I'm new to regular exprsesions so I really have no idea how to do this.

Let's say I have a string like the one below.  I have an array of the usernames...Let's call it $user_array.  How would I go about searching for, and replacing the string under each user with a string called $replacement?  Or better yet, how would I just capture the text for each user using preg_match?  It needs to be able to capture multiple lines and any character thrown it's way.  I don't need the whole logic behind it, just the preg_replace/preg_match statement.  Thanks guys

[username=User1]
Some notes on this user go here
[username=User2]
More notes
on user two go
here
[username=User3]
These are notes
that I have kept for
this
particular user





#2 effigy

effigy
  • Staff Alumni
  • Advanced Member
  • 3,600 posts
  • LocationIL

Posted 21 August 2006 - 09:10 PM

<pre>
<?php

	$data = <<<DATA
[username=User1]
Some notes on this user go here
[username=User2]
More notes
on user two go
here
[username=User3]
These are notes
that I have kept for
this
particular user	
DATA;
	$data_array = explode("\n", $data);
	### The above can be handled with the file function.
	
	### The name.
	$user = '';
	### The data.
	$user_data = '';
	### The result.
	$result = array();
	foreach ($data_array as $piece) {
		### If a user name is found...
		if (preg_match('/\[username=(.+?)\]/',$piece, $matches)) {
			### ...and there is data...
			if ($user_data) {
				### ...add the user to the array with their data...
				$result[$user] = $user_data;
				### ...and empty the data.
				$user_data = '';
			}
			### ...set the new user that was found.
			$user = $matches[1];
		}
		### No user name was found, tack onto the data.
		else {
			$user_data .= $piece;
		}
	}
	### "Flush."
	$result[$user] = $user_data;
	
	print_r($result);
?>
</pre>

Regexp | Unicode Article | Letter Database
/\A(e)?((1)?ff(?:(?:ig)?y)?|f(?:ig)?)\z/

#3 mapunk

mapunk
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 21 August 2006 - 09:20 PM

Thanks a lot, I'll check it out and let you know how it goes  :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users