Jayarathina Madharasan
Jayarathina Madharasan

Reputation: 240

PHP preg_replace not working as intended in this code

My intention is to remove any attribute which does not have value.

Here is my Code:

<?php
$srcTxt = "
|title=
|Row18={{Timeline row
  |from=
  |to=2000
  |1-text= TYRR consolidation
  |1-at= 1904
  |2-text= TYRR and TFC takeover
  |2-at= 1927
  |3-text= private bus services acquisition
  |3-at= 1954
|Row18={{Scale row|
  |from=1840
  |to=2000
  |increment=40
  }}
}} ";

$srcTxt = preg_replace("/^ *.*= *$/m", "", $srcTxt);

echo ($srcTxt);

?>

The expected output is to remove |title= and |from= which do not have any values assigned to them.

This works perfectly here But not so when I run it locally in my system. What might be the issue?

Upvotes: 0

Views: 114

Answers (1)

revo
revo

Reputation: 48711

<?php
$srcTxt = "
|title=
|Row18={{Timeline row
  |from=
  |to=2000
  |1-text= TYRR consolidation
  |1-at= 1904
  |2-text= TYRR and TFC takeover
  |2-at= 1927
  |3-text= private bus services acquisition
  |3-at= 1954
|Row18={{Scale row|
  |from=1840
  |to=2000
  |increment=40
  }}
}} ";

$srcTxt = trim(preg_replace("/(.+?)=\s*\n/", '', $srcTxt));
echo $srcTxt ;

Output:

|Row18={{Timeline row
  |to=2000
  |1-text= TYRR consolidation
  |1-at= 1904
  |2-text= TYRR and TFC takeover
  |2-at= 1927
  |3-text= private bus services acquisition
  |3-at= 1954
|Row18={{Scale row|
  |from=1840
  |to=2000
  |increment=40
  }}
}}

Upvotes: 1

Related Questions