Jump to content

[SOLVED] Match/replace 2 patterns in one pass


esdaniel

Recommended Posts

A cry for help...

 

Sample text:

 

The cat sat on the [[straw|mat]].

The cat hoped he would jump through the [[windows]] and catch the [[feathered variety|bird on the branch]].

 

The regex pattern I'm struggling to put together would match all text between "|" and "]]" or where there is no "|" then all text between "[[" and "]]", as per the text above this regex would then match the following strings:

 

"mat"

"windows"

"bird on the branch"

 

Allowing me to replace the text between and including [[ and ]] with the strings in the match.

 

Any guidance/help would be greatly appreciated.

Link to comment
Share on other sites

I think i see what you mean... try this guy

 

<pre><?php

$subject = 'The cat sat on the [[straw|mat]].
The cat hoped he would jump through the [[windows]] and catch the [[feathered variety|bird on the branch]].';

$array = getValues( $subject );

print_r( $array );

function getValues( $input ) {

$regex = '/\[\[([^|\]]++)(?:\|([^\]]++)){0,1}/';
if( preg_match_all($regex, $input, $matches, PREG_SET_ORDER) < 1 )
	return array();

$return = array();
foreach( $matches as $m ) {
	if( isset($m[2]) === FALSE )
		$return[] = $m[1];
	else
		$return[] = $m[2];
}
return $return;

}

?></pre>

Link to comment
Share on other sites

<pre>
<?php
$subject = 'The cat sat on the [[straw|mat]]. The cat hoped he would jump through the [[windows]] and catch the [[feathered variety|bird on the branch]].';

preg_match_all(
	'%\[\[(?:[^]|]+\|)?([^]]+)\]\]%',
	$subject,
	$matches
);
$matches = $matches[1];
print_r($matches);
?>
</pre>

Link to comment
Share on other sites

Thank you Discomatt and Effigy... the second response is ideal as it allows me to use str_replace and makes the resulting code much more eloquent/readable in that I don't have to code-around varying array sizes as per discomatt's initial solution i.e.

 

preg_match_all('%\[\[(?:[^]|]+\|)?([^]]+)\]\]%',$content,$replace);

$content = str_replace($replace[0],$replace[1],$content);

 

I'm very pleased to have found this forum and hope I can give something back in the near future.

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.