编辑一个改变字符串最后一次出现的url,并检查它是否存在于PHP中


Edit an url changing last occurence of a string in it and check if it exists in PHP

我有一个字符串,它是一个url,例如

www.example.com/something/2/other_stuff/2/1

我有一个int,比方说在这个例子中是2。

我想创建一个新的url,用下一个替换最后一次出现的int。所以,在这个例子中,我想要的是:

 www.example.com/something/2/other_stuff/3/1

url可以用任何方式编写,它没有特定的模式。一旦创建了新的链接,我还需要检查它是否真的存在于网络上。你知道吗?

由于您已经有了一个字符串,并且知道要检查哪个整数,下面的解决方案应该有效。

//Make sure you sanitize the url
function yourAnswer($url, $yourInt){
 $offset = strrpos($url, $yourInt);
 if(!$offset)
    return FALSE; //The integer was not found in the url
 $url[$offset] = $yourInt + 1;
 $url = "http://".$url ; //Assuming only http
 // Now we check whether the page exists
 $file_headers = @get_headers($url);
 if($file_headers[0] == 'HTTP/1.1 404 Not Found')
    return FALSE;
 return TRUE;
 }
//In your function call make sure you quote the number, else strrpos looks for the character value of that number
//yourAnswer("www.example.com/something/2/other_stuff/2/1",'2');`

关于检查文件是否存在的进一步参考:如何通过PHP检查URL是否存在?