1

How can I search for the word "Box" within the html code below:

<p>Text here ok</p>
<h4>
Box 1.2</h4>
<p>Text here ok</p>

and have the output as follows?

<p>Text here ok</p>
<h4><a name="box1.2"></a>Box 1.2</h4>
<p>Text here ok</p>

Note the line break between <h4> and Box needs to be removed. The other thing is I will have "Box 2.0", "Box 2.3", etc. so only the word "Box" has the matching pattern.

2
  • use str_replace() to do it Commented May 6, 2013 at 7:54
  • Will it always be in <h4> tag or it can be inside other HTML tags as well (like div, p, span etc)? Commented May 6, 2013 at 7:55

2 Answers 2

1

Here's something to get you going.

<?php
$html = '<p>Text here ok</p>
<h4>
Box 1.2</h4>
<p>Text here ok</p>';

$html = preg_replace_callback('~[\r\n]?Box\s+[\d.]+~', function($match){
    $value  = str_replace(array("\r", "\n"), null, $match[0]);
    $name   = str_replace(' ', null, strtolower($value));
    return sprintf('<a name="%s"></a>%s', $name, $value);
}, $html);

echo $html;

/*
    <p>Text here ok</p>
    <h4><a name="box1.2"></a>Box 1.2</h4>
    <p>Text here ok</p>
*/
Sign up to request clarification or add additional context in comments.

1 Comment

@anubhava: yes, may be any other tags but the concern is the word "Box". It's part of another file which looks for the boxed anchors in here.
0

Using PHP:

$str = '<p>Text here ok</p>
<h4>
Box 1.2</h4>
<p>Text here ok</p>';

$new = preg_replace('/\s*(box)\s*(\d+(:?\.\d+)?)/i', '<a name="$1$2">$1 $2</a>', $str);
echo $new;

Explanation:

/ #START delimiter
    \s* #match spaces/newlines (optional/several)
    (box) #match "box" and group it (this will be used as $1)
    \s* #match spaces/newlines (optional/several)
    (\d+(:?\.\d+)?) #match a number (decimal part is optional) and group it (this will be used as $2)
/ #END delimiter
i #regex modifier: i => case insensitive

1 Comment

(\d+(:?\.\d+)) -> (\d+(?:\.\d+)?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.