The other day I was working on a project that required me to extract a numeric ID from the current page’s URL. The problem was that the ID could either be at the end of the URL string or in the middle, depending if there were any parameters added on or not. Here is how I worked around the problem by looping through each character of the string.
Because the first part of the URL was formatted normally I could use a combination of strpos()
and substr()
to find the part of the string that contained the ID as well as all the characters that followed it (I could have used regex here, but I prefer to avoid using it if I can help it). This still left me with the problem of getting the ID out of that string, as the actual number could be any length. Luckily for me, the ID was immediately followed by a non-numeric character, so I came up with a solution where I could loop through each character in the string and use each one for the required ID, but stop the loop when I hit the first character that was not a number. In the interest of sharing some useful code, here is the simple snippet that I used to loop through the string along with my use case:
Leave a Reply