PHP: Does a String start with a specific String or Character?
Question by Guest | 2014-02-28 at 18:49
I would like to figure out, whether a given string is starting with a specific other string.
For example, when checking the input of an Internet address, I would like to check whether the input string begins with "http" or "www".
Unfortunately, I have not found a fitting function in PHP. Can someone help me?
Related Topics
MySQL: Line Breaks in MySQL
Tip | 0 Comments
JavaScript: Remove last character from string
Tip | 5 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
Android Getting Sound Levels
Open Question | 1 Answer
PHP: Current Date and Time
Tutorial | 0 Comments
HTML Form: Redirection depending on Radiobutton or Checkbox State
Tutorial | 0 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
Surely, there are several solutions for this issue. One of this is:
The function strpos() returns the position of the search string. If the position is 0, the string is beginning with the search string.
2014-02-28 at 20:47
Another possibilty is to use substr() instead. I take the same example:
With substr(), you can cut a part of a string. In the first case from the example above 3 characters starting at the first character and in the second case 4 characters. So, you have to adjust the 3 and 3 to the length of the search string.
Alternatively, you can also write a more general function like this:
In this example, I have replaced the codec length with strlen($s). With this, the required length is determined dynamically.
2014-03-01 at 15:21
You can also have a look at my article about strStart and strEnd functions in PHP.
The strStart function introduced in this article can be used exactly for the purpose of the question.
2014-03-15 at 21:36
And here is just another possibility. This time using strncmp():
With strncmp() you are comparing the string passed as first parameter with the string passed as the second parameter. The comparison is done on the length specified in the third parameter.
For equal strings, the result is 0.
2014-03-30 at 00:06