Jump to content

multi line and single line.


The Little Guy

Recommended Posts

$html = '<?xml version="1.0" encoding="UTF-8"?>
<root>
<!--
People who are 25 years old
-->
<names age="25">
	<name>Ryan</name>
	<name>Bill</name>
	<name>Bob</name>
</names>
<!-- People who are 45 years old -->
<names age="45">
	<name>Roy</name>
	<name>Jill</name>
	<name>Jimmy</name>
</names>
</root>';

$com = '#34803a';
echo preg_replace('~(<\!--.*?-->)~s', '<span style="font-style:italic;color:'.$com.';">$1</span>', $html);

 

I have the above regexp and it works for these lines:

	<!--
People who are 25 years old
-->

but it doesn't work for this one:

	<!-- People who are 45 years old -->

 

What can I do to fix this so it works for both?

Visual Example: http://tests.phpsnips.com/phpLive/examples/misc/highlight.php

Link to comment
https://forums.phpfreaks.com/topic/248349-multi-line-and-single-line/
Share on other sites

Then it must be one of the others, and I think that it is the 4th one messing up the comments...

 

$tag = '#0000ff';
$att = '#ff0000';
$val = '#8000ff';
$com = '#34803a';
$find = array(
'~(\s[a-z].*?=)~',						// Highlight the attributes
'~(<\!--.*?-->)~s',				// Hightlight comments
'~("[a-zA-Z0-9\/].*?")~',		// Highlight the values
'~(<[a-zA-Z!?].*?>)~',			// Highlight the beginning of the opening tag
'~(</[a-zA-Z].*?>)~',				// Highlight the closing tag
'~(&.*?~',						// Stylize HTML entities
);
$replace = array(
'<span style="color:'.$att.';">$1</span>',
'<span style="font-style:italic;color:'.$com.';">$1</span>',
'<span style="color:'.$val.';">$1</span>',
'<span style="color:'.$tag.';">$1</span>',
'<span style="color:'.$tag.';">$1</span>',
'<span style="font-style:italic;">$1</span>',
);

Comments should be handled separately from everything else.

 

The strategy I use for that, which more commonly occurs with BBCode, is to preg_split using comments as delimiters. Alternating, one will be regular XML and the next will be a comment.

$iscomment = false; // starts off outside comments
foreach (preg_split('//s', $xml, -1, PREG_SPLIT_DELIM_CAPTURE) as $split) {
if ($iscomment) {
	// just a comment
} else {
	// not a comment. format
}
$iscomment = !$iscomment;
}

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.