fish man
fish man

Reputation: 2700

php preg_replace words last part

$str='<p>http://domain.com/1.html?u=1234576</p><p>http://domain.com/2.html?u=2345678</p><p>http://domain.com/3.html?u=3456789</p><p>http://domain.com/4.html?u=56789</p>';
$str = preg_replace('/.html\?(.*?)/','.html',$str);
echo $str;

I need get

<p>http://domain.com/1.html</p>
<p>http://domain.com/2.html</p>
<p>http://domain.com/3.html</p>
<p>http://domain.com/4.html</p>

remove ?u=*number* from every words last part. thanks.

Upvotes: 0

Views: 275

Answers (3)

Kristoffer Bohmann
Kristoffer Bohmann

Reputation: 4094

This code will load the url's into an array so they can be handled on the fly:

$str = '<p>http://domain.com/1.html?u=1234576</p><p>http://domain.com/2.html?u=2345678</p><p>http://domain.com/3.html?u=3456789</p><p>http://domain.com/4.html?u=56789</p>';
$str = str_replace("<p>","",$str);
$links = preg_split('`\?.*?</p>`', $str,-1,PREG_SPLIT_NO_EMPTY);

foreach($links as $v) {
    echo "<p>".$v."</p>";
}

Upvotes: 0

rzetterberg
rzetterberg

Reputation: 10268

An alternative to the other answers:

preg_replace("/<p>([^?]*)\?[^<]*<\/p>/", "<p>$1</p>", $input);

This will match all types of urls with url variables, not only the ones with html-files in them.

For example, you can also extract these types of values:

<p>http://domain.com/1.php?u=1234576</p>
<p>http://domain.com?u=1234576</p>
<p>http://domain.com</p>
<p>http://domain.com/pages/users?uid=123</p>

With an output of:

<p>http://domain.com/1.php</p>
<p>http://domain.com</p>
<p>http://domain.com</p>
<p>http://domain.com/pages/users</p>

Upvotes: 1

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22162

Change this line:

$str = preg_replace('/.html\?(.*?)/','.html',$str);

into this:

$str = preg_replace('/.html\?(.*?)</','.html<',$str);

Upvotes: 1

Related Questions