How to traverse through the long string and replace certain block with certain text?
I need to replace <slot> slot_name </slot>
with a <?php !include_slot('slot_name')?>
in the text that I read from file
<table class="layout-table" id="layout1">
<tr>
<td class="slot" id="slot1" colspan="2">
<slot>
slot_name
</s开发者_JAVA技巧lot>
</td>
</tr>
<tr>
<td class="slot" id="slot2" rowspan="2">
<slot>
slot_name
</slot>
</td>
<td class="slot" id="slot3">
<slot>
slot_name
</slot>
</td>
</tr>
</table>
could anybody give me some directions as I had not really worked with this kind of traversing before. The problem is to iterate through the text and at the same time change the block with respect to the "slot_name"
Since you appear to be doing a straight search-and-replace, and not actually parsing HTML or XML, doing a regex here is a perfectly valid option.
(If you might have existing PHP containing this slot stuff, or otherwise start getting into nested tags, commenting, and similar, you'll be wanting to use a DOM parser.)
This one uses lookahead/lookbehind to mean that the whole match is slot_name:
(?<=<slot>\s*)\w+(?=\s*</slot>)
Alternatively, this will place the slot_name into capture group 1:
<slot>\s*(\w+)\s*</slot>
(These both assume that slot_name is comprised of "word characters", which is alphanumerics and underscore.)
Explanation of the first one is:
(?<= # begin positive lookbehind
<slot> # literal text
\s* # zero or more whitespace
) # end positive lookbehind
\w+ # one or more word characters
(?= # begin positive lookahead
\s* # zero or more whitespace
</slot> # literal text
) # end positive lookahead
The second lacks the lookaheads, but uses simple cature group syntax (
...)
but is otherwise no new syntax.
(If you do want to learn regular expressions fully, regular-expressions.info has a tutorial worth completing.)
So yeah, either one of these lines will do it:
preg_replace( "/(?<=<slot>\s*)\w+(?=\s*<\/slot>)/" , "<?php !include_slot('$0')?>" , $Input )
preg_replace( "/<slot>(\w+)\s*<\/slot>/" , "<?php !include_slot('$1')?>" , $Input )
(Note the escaped forward slashes - alternatively you can use different characters at the start/end to delimit the regex.)
Use a DOM-based XML parser. See today's topic du jour, http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html .
An XML parser can do the job. You can also do it the dirty way with a str_replace or a regular expression.
If the markup is as simple as that, and it'll only ever be <slot>[Whitespace]slot_name[Whitespace]</slot>
then a regular expression will be absolutely fine, and an XML parser will be overkill.
If you want to learn regex, go to Regular-Expressions.info.
If you find yourself adding more and more functionality, and it stops being as simple as the skeleton outlined above, then by all means start using a proper parser. Otherwise, do the simplest thing that could possibly work.
精彩评论