简体   繁体   中英

Change ID in last paragraph with preg_replace (PHP/Regex)

The following script gives every paragraph a numerical ID, beginning with [p class="pfirst" id="1"] and [p id="2"], where $Article is an article stored in a database. (Only the first paragraph has a class.)

If there are ten articles in a paragraph, the last paragraph tag will be [p id="10"]. Can any regex wizards tell me how to modify it so that the last paragraph always displays as [p id="Last"] instead of a numerical ID?

$c = 1;
$r = preg_replace('/(<p( [^>]+)?>)/ie', '"<p\2 id=\"" . $c++ . "\">"', $Article);
$Article = $r;

Here's the entire script...

$SeaURL = str_replace('Washington/', '', $MyURL);

$stm = $pdo->prepare("SELECT P.URL, P.Site, ART.Article
 FROM people P
 LEFT JOIN people_articles ART ON ART.URL = P.URL
 WHERE P.URL LIKE :MyURL AND P.Site = :MySiteID
 GROUP BY Class");
$stm->execute(array(
 'MySiteID'=>$MySiteID, 
 'MyURL'=>'%'.$MyURL.'%'
));

while ($row = $stm->fetch())
{
 $Article = $row['Article'];
}

$c = 1;
$r = preg_replace('/(<p( [^>]+)?>)/ie', '"<p\2 id=\"" . $c++ . "\">"', $Article);
$Article = $r;

 $Content = str_replace('$Name_Common', '<span style="color: #900"><strong>'.$Common.'</strong></span>', $Article);

echo $Content;

One way of doing it:

//$Article ="<p class=\"pfirst\">paragraph 1</p><p>paragraph 2</p><p>paragraph 3</p>";
$c = 1;
$r = preg_replace('/(<p( [^>]+)?>)/ie', '"<p\2 id=\"" . $c++ . "\">"', $Article);
$r = preg_replace('/(<p.*?)id="'.($c-1).'"(>)/i', '\1id="Last"\2', $r);
$Article = $r;

Note: it is a dangerous way of playing with e modifier, though, cause some of the code in your p tags becomes php executable.

EDIT: Also the e modifier is being depricated, so below is a better and safer alternative:

$c = 1;
$r = preg_replace_callback('/(<p( [^>]+)?>)/i', function ($res) {
   global $c;
   return '<p'.$res[2].' id="'.intval($c++).'">';
}, $Article);
$r = preg_replace('/(<p.*?)id="'.($c-1).'"(>)/i', '\1id="Last"\2', $r);
$Article = $r;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM