[PHP] preg_replace problem

Soldato
Joined
12 Apr 2004
Posts
11,788
Location
Somewhere
I want to replace all instances of a certain character sequence, say A, that occur either at the start of a line or after a sequence of A beginning at the start of a line.

Using | and > as an example characters, this:
Code:
some|text|

|some text
||some more text
|||even more text

...should become this:
Code:
some|text| (these ones aren't replaced as they're not at the start of a line)

>some text
>>some more text
>>>even more text

Can anyone help me? I'm useless with regexes :(
 
Last edited:
jdickerson said:
Code:
str_replace("|", ">","$string");

?
That will replace all instances of |, whereas I only want to replace either instances that are at the beginning of a line, or immediately follow a sequence of |s that starts at the beginning of a line.
 
psyr33n said:
http://php.net/strpos
EDIT: Whoops, bad idea: use /^ - start of string.
Yeah that's what I tried but it doesn't handle repeated character sequences though :(

I've come up with this, though (jdickerson's post gave me the idea):
Code:
// Normalise new line characters and split by line.
$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "\n", $text);
$lines = explode("\n", $text);

$sequence = '>';
$replacement = '>';
$sequenceLength = strlen($sequence);
$replacementLength = strlen($replacement);
$processedLines = array();
foreach ($lines as $line)
{
	// Process the line.
	for ($i = 0; $i < strlen($line); $i += $sequenceLength)
	{
		// Test the current part of the string to see if it matches.
		$segment = substr($line, $i, $sequenceLength);
		if ($segment == $sequence)
		{
			// Replace.
			$line = substr_replace($line, $replacement, $i, $sequenceLength);
			
			// Modify counter accordingly so that the loop continues at the right place.
			$i += $replacementLength - $sequenceLength;
		}
		else
		{
			// We've reached part of the string that doesn't match the sequence, so stop processing.
			break;
		}
	}
	
	$processedLines[] = $line;
}

$text = implode("\n", $processedLines);

It's rather crude and (very) long-winded but it does the job. Would be nice to be able to do it all with a regex, though, if anyone knows how :)
 
Last edited:
robmiller said:
Code:
$str = preg_replace_callback("#^(\|+)#m", create_function('$s', 'return str_repeat(">", strlen($s[0]));'), $str);

(You can probably do this in pure regex but I DON'T CARE)

*returns to his exile*
Works perfect like. Thanks!
 
Back
Top Bottom