cicakman
cicakman

Reputation: 1990

search and replace thousands of lines php

I am very new to using preg_replace and such so please bear with me.

I have few hundreds line that contains this line

<strong>[*<a title="*" name="*"></a>]</strong><br /> Lorem ipsum

* on above code denotes that number such as 1,2,3

What i want to achieve is that

*. Lorem Ipsum

Example, 1. Lorem ipsum, 2. Lorem ipsum

What would be the best way to achieve it? Thanks.

sample text

<strong>[1<a title="1" name="1"></a>]</strong><br /> Lorem ipsum 12345<br /> <strong>[2<a title="2" name="2"></a>]</strong><br /> lorem ipsum asdasd<br /> <strong>[3<a title="3" name="3"></a>]</strong><br /> lorem ipsum asdsadasdasdasd<br />

it goes way up to hundreds

Upvotes: 2

Views: 127

Answers (3)

Toto
Toto

Reputation: 91385

How about:

$output = preg_replace('~^<strong>\[(\d+)<.*?<br\s*/>~', '$1. ', $input);

explanation:

~             : regex delimiter
  ^           : start of line
  <strong>    : <strong> as is
  \[          : an open square bracket
  (\d+)       : capture one or more digits
  <.*?        : > followed by any number of any char
  <br\s*/>    : <br/> or <br />
~

And replace all that match by the first captured group (ie. the digits) followed by a dot and a space.

Edit according to comments:

$input = '<strong>[1<a title="1" name="1"></a>]</strong><br /> Lorem ipsum 12345<br /> <strong>[2<a title="2" name="2"></a>]</strong><br /> lorem ipsum asdasd<br /> <strong>[3<a title="3" name="3"></a>]</strong><br /> lorem ipsum asdsadasdasdasd<br />';
$output = preg_replace('~\s*<strong>\[(\d+)<.*?<br\s*/>(.*?)(?:<br />|$)~', "$1. $2\n", $input);
echo $output,"\n";

output:

1.  Lorem ipsum 12345
2.  lorem ipsum asdasd
3.  lorem ipsum asdsadasdasdasd

Upvotes: 3

Egor Sazanovich
Egor Sazanovich

Reputation: 5089

$x=1;
$result = preg_replace_callback (
'%<strong(.*?)strong><br.?/>.?(.*?)\r\n%sim'
, create_function(
          '$matches,$x',
          'return $x++.$matches[1];'
), $input );

Something like this

Upvotes: 1

FtDRbwLXw6
FtDRbwLXw6

Reputation: 28889

One method would be to use preg_replace_callback() and create a function to increment a variable and substitute the * with the current value of that variable (though I think you may have to use a global variable for this, which is generally considered bad practice).

Outside of that, I think you'd have to do it iteratively (i.e. in a loop).

Upvotes: 1

Related Questions