Reputation: 119
On my website I have some urls that look like this.
http://example.com/our-post-name-here-number-one-81347.html our post name number one
http://example.com/our-post-name-here-number-two-81348.html our post name number two
http://example.com/our-post-name-here-number-three-81349.html our post name number three
And I am needing to get the part right befor the .html
which contains a random number, under no stance will this number ever be the same.
Currently, I am storing these urls inside of a .txt
file which has the title of the post also included, and exploding via this method below.
$array = explode("\n", file_get_contents('http://example.com/urls/delete.txt'));
foreach ($array as $item) {
$removed = "copyright";
$nothing = "";
$url = explode(" ", $item);
$data = $url[0];
$explode = explode(".html", $data);
// other functions
$primary = $explode[0];
print $primary;
print '<br>';
}
The above code is currently returning this.
http://example.com/our-post-name-here-number-one-81347
http://example.com/our-post-name-here-number-two-81348
http://example.com/our-post-name-here-number-three-81349
When I only want it to return this 81347
81348
81349
.
Upvotes: 2
Views: 48
Reputation: 1982
I would use regex.
$array = explode("\n", file_get_contents('http://example.com/urls/delete.txt'));
foreach ($array as $item)
{
$regex = "/.*-([\d]+)\.html.*$/";
preg_match ( $regex , $item , $matches );
$primary = $matches[1];
print $primary;
print '<br>';
}
Upvotes: 3
Reputation: 7746
Pass it to this function:
function url_post_id($url) {
$i = strripos($url, "-");
$j = stripos($url, ".", $i);
return substr($url, $i+1, $j-$i-1);
}
Upvotes: 1
Reputation: 9957
If the same format is guaranteed, you can split one more time by -
, and get the last element with array_pop()
:
$pieces = explode("-", $primary);
$number = array_pop($pieces);
print $number;
Upvotes: 0