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.

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>

<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>

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.