Jump to content

preg_match problems


Zugzwangle

Recommended Posts

Hi... I have a string (called $textData) with the following format:

1. e4 {[%emt 0:00:10]} c5 {[%emt 0:00:04]} 2. c3 {[%emt 0:02:15]}

etc

 

I need to replace the square brackets/special chars within that string with " "...  so my first thought was to use preg_match to find the matches.. then preg_replace/str_replace to update them.

 

To find the patterns, I think this is correct:

preg_match('/\{([^\}]*)\}/', $textData, $matches);
	echo print_r($matches, true);
// returns Array ( 
[0] => {[%emt 0:00:10]} 
[1] => [%emt 0:00:10]
) 
// returns nothing else

 

I expected the preg_match to search through the whole of $textData.  Then I could replace the square brackets/special chars with a spaces. 

 

Thank you for your time!!

Link to comment
Share on other sites

Oh right.. I didnt know of the function preg_match_all() !!!  Ok so, now I have the matches:

preg_match_all('/\{([^\}]*)\}/', $textData, $matches);
//Outputs:
//Array ( [0] => 
//Array ( [0] => {[%emt 0:00:10]} 
//[1] => {[%emt 0:00:04]} 
//[2] => {[%emt 0:02:15]} 
//[3] => {[%emt 0: 00:14]}
//))

So first stage done.. I can now access the elements of $matches..  Now I have to use preg_replace/str_replace to update them.. I'm not sure which yet!

 

Link to comment
Share on other sites

ok I worked it out... :

		$splitTextData = preg_split("/\{([^\}]*)\}/", $textData);

	preg_match_all('/\{([^\}]*)\}/', $textData, $matches);
	foreach ($matches[0] as $matVal)
	{
		//echo $matVal;
		$matVal2 = preg_replace('/\[/', '', $matVal);
		$matVal3 = preg_replace('/\]/', '', $matVal2);
		$matVal4 = preg_replace('/\%/', '', $matVal3);
		$matVal5 = preg_replace('/emt/', '', $matVal4);
		//$matVal5 = preg_replace('/[a-zA-]/', '', $matVal4);
		$matchArr[] = $matVal5;
	}
	//echo print_r($matchArr, true).'<br>';
	foreach ($splitTextData as $tdKey => $tdVal)
	{
		$comboVal[] = $tdVal.$matchArr[$tdKey];
	}
	//echo print_r($comboVal, true);
	$textData2 = join(" ", $comboVal);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.