00 Votes

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?

ReplyPositiveNegativeDateVotes
0Best Answer0 Votes

Surely, there are several solutions for this issue. One of this is:

$s = 'www.askingbox.com';

if (strpos($s, 'www') === 0) {
   // $s starts with "www"
}

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

ReplyPositive Negative
00 Votes

Another possibilty is to use substr() instead. I take the same example:

$s = 'www.askingbox.com';

if (substr($s, 0, 3) === 'www') {
  // $s starts with "www"
}

if (substr($s, 0, 4) === 'http') {
  // $s starts with "http"
}

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:

if (substr($s, 0, strlen($s) === 'www') {
   // $s starts with "www"
}

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

ReplyPositive Negative
00 Votes

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

ReplyPositive Negative
00 Votes

And here is just another possibility. This time using strncmp():

$s = 'abcdefgh';
$search = 'abc';

if (strncmp($s, $search, strlen($search)) === 0) {
  // $s starts with $search
}

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

ReplyPositive Negative
Reply

Related Topics

Android Getting Sound Levels

Open Question | 1 Answer

PHP: Current Date and Time

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.