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
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>',
);

Link to comment
Share on other sites

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

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.