I am using preg_replace() function to replace new lines in my code string with ol tag of html to display the following string :
<h2>Hello world</h2>
This is a new line.
This is also a new line. I am not a new line.
as
1. <h2>Hello world</h2>
2. This is a new line.
3. .....blank line....
4. This is also a new line. I am not a new line.
The code bellow matches new lines, and replaces them,
echo preg_replace("/(
+)([^
]+)/","<ol start='0'><li>$1$2</li></ol>",$code);
it returns the wired output
0. <h2>Hello world</h2>
0. This is a new line.
0. .....blank line....
0. This is also a new line. I am not a new line.
so i thought i would change "0" to "1" in ol tag
then the result was
1. <h2>Hello world</h2>
1. This is a new line.
1. .....blank line....
1. This is also a new line. I am not a new line.
How can I get my expected output ?
please help.
As you need to do basic logic (a counter) a way to archive this is by using the preg_replace_callback
function like on this example:
<?php
$text = "<h2>Hello world</h2>
This is a new line.
This is also a new line. I am not a new line.
";
print "
BEFORE:
$text";
$text = preg_replace_callback(
'/([^
]*)(
)/',
function ($matches) {
global $number;
return "<ol start='" . ++$number . "'><li>" . $matches[1] . "</li></ol>
";
},
$text
);
print "
AFTER:
$text";
More information: http://php.net/manual/en/function.preg-replace-callback.php