# Adding a more logical string slicing function to PHP

- Thread: https://externals.io/message/51745
- Original archive: https://news-web.php.net/php.internals/51745
- Started by Dan Birken on 2011-03-30T06:06:37+00:00
- Messages: 37
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/51745.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #51745 — Dan Birken — 2011-03-30T06:06:37+00:00

URL: https://externals.io/message/51745#51745

My apologizes if I am bringing up a topic that has been discussed before,
this is my first time wading into the PHP developers lists and I couldn't
find anything particularly relevant with the search.

Here is a bug I submitted over the weekend (
http://bugs.php.net/bug.php?id=54387) with an attached patch that adds a
str_slice() function into PHP.  This function is just a very simple string
slicing function, with the logical interface of str_slice(string, start,
[end]).  It is of course meant to replace `substr()` as an interface for
string slicing.

I detailed the reasons I submitted the patch in the bug a little bit, but
the main reason is that I think the `substr()` function is really overly
confusing and just not an intuitive method of string slicing, which is
exceedingly common functionality.  I realize we don't want to go around
adding lots of random little functions into the language that don't offer
much, but the problem with that is that if we have a function like `substr()`
with an unusual and unintuitive interface, it becomes unchangeable due to
legacy issues and then you can never improve.  I think this particular
functionality is important enough to offer an updated interface.  In the bug
I also pointed to two related bugs that would be essentially fixed with this
patch.

-Dan

---

## #51746 — Lars Schultz — 2011-03-30T06:22:48+00:00

URL: https://externals.io/message/51745#51746 · In reply to: #51745

I just love `substr()` and I think all other languages got it wrong;)

Seriously...it behaves the same as implementations in other languages as 
long as values are positive, right? how is that counter-intuitive? How 
do other languages handle negative values?

Am 30.03.2011 08:06, schrieb Dan Birken:
> My apologizes if I am bringing up a topic that has been discussed before,
> this is my first time wading into the PHP developers lists and I couldn't
> find anything particularly relevant with the search.
>
> Here is a bug I submitted over the weekend (
> http://bugs.php.net/bug.php?id=54387) with an attached patch that adds a
> str_slice() function into PHP.  This function is just a very simple string
> slicing function, with the logical interface of str_slice(string, start,
> [end]).  It is of course meant to replace `substr()` as an interface for
> string slicing.
>
> I detailed the reasons I submitted the patch in the bug a little bit, but
> the main reason is that I think the `substr()` function is really overly
> confusing and just not an intuitive method of string slicing, which is
> exceedingly common functionality.  I realize we don't want to go around
> adding lots of random little functions into the language that don't offer
> much, but the problem with that is that if we have a function like `substr()`
> with an unusual and unintuitive interface, it becomes unchangeable due to
> legacy issues and then you can never improve.  I think this particular
> functionality is important enough to offer an updated interface.  In the bug
> I also pointed to two related bugs that would be essentially fixed with this
> patch.
>
> -Dan

---

## #51747 — Dan Birken — 2011-03-30T07:42:20+00:00

URL: https://externals.io/message/51745#51747 · In reply to: #51746

I think when the values are positive everything is mostly great.  I think
when the values are negative is where the main problems are.  Both the C
function strncpy() and the C++ strings `substr()` function only support
positive values for length AFAIK.

I just think it is very unintuitive for the first parameter always to be a
position, and the 2nd parameter to be a length if the value is positive, and
a position if the value is negative.

substr('string', 1, 2); // Goes from position 1 to position 3
substr('string', -2, -1); // Goes from position -2 to position -1

So here is the same kind of thing in python, which uses [start, end):
string[1:2] ==> 't'
string[-2:-1] ==> 'n'

And ruby, which uses [start, end]:
"string"[2..3] ==> 'tr'
"string"[-2:-1] ==> 'ng'

Both of these languages use positions for positive and negative values.  In
addition, in both of these languages if you slice a string impossibly, both
of them return an empy string as opposed to false, which just seems more
intuitive to me.

I don't think this function is particularly novel, I just think both
returning an empty string on impossible slicing and slicing based on
positions are improvements, and combined I think this function is noticeably
more durable and readable than `substr()`.

-Dan

On Tue, Mar 29, 2011 at 11:22 PM, Lars Schultz <lars.schultz@toolpark.com>wrote:

> I just love `substr()` and I think all other languages got it wrong;)
>
> Seriously...it behaves the same as implementations in other languages as
> long as values are positive, right? how is that counter-intuitive? How do
> other languages handle negative values?
>
> Am 30.03.2011 08:06, schrieb Dan Birken:
>
>  My apologizes if I am bringing up a topic that has been discussed before,
> > […]

---

## #51748 — Hannes Landeholm — 2011-03-30T13:05:22+00:00

URL: https://externals.io/message/51745#51748 · In reply to: #51747

PHP's `substr()` is awesome and that comes from a person that code in at least
5 different languages daily. Parsing is a problem in many real-world
problems and substr currently works great for that purpose. You work with
two parameters: offset and length of parsing. Since meaning of a negative
offset/length when sub-stringing is intuitively undefined, PHP has reserved
these ranges for two common usecases: offsets from the end of the string and
truncation length.

"I just think it is very unintuitive for the first parameter always to be a
position, and the 2nd parameter to be a length if the value is positive, and
a position if the value is negative."

The first parameter is either an offset from start or offset from end - the
second parameter is either a length or a truncation length. I don't see why
this would be unintuitive? Perhaps you get confused by other languages that
just work with offsets.

In most real world parsing scenarios I've worked with offsets and lengths,
so the current substr definition gets my job done fastest without doubt.
Let's have a real world example "Parse through the data in chunks of 64
bytes at a time." In PHP this is simple, just take the current offset and a
length of 64. In python you'd have to add 64 to the current offset and put
into the second offset parameter = you have to think more and write more
code instead of just working with the length directly.

"Returning `FALSE` when start + length parameters are invalid.  This is
annoying
because when using this function you always have to deal with this `FALSE` 
case if
you need a string. "

Guess what this code outputs?

var_dump((string) \substr("foo", 5, 6));

Now try this and you'll understand why this is basically never a problem
that substr outputs false and why you don't even have to think about it:

var_dump(\substr("foo", 5, 6) == "", (string) false, false == "");

Welcome to PHP. To be honest this criticism pretty much falls in the "from
person that comes from another language X and is annoyed that every little
detail isn't exactly the same"-category. Just make your own `substr()`
function that uses the behavior you expect if you don't like the native
version. Although that's bad practice - the best solution is to get used to
it. And if you have an urge to write about your experience with a new
language I suggest you do it in a blog instead of posting it in the
internals mailing list...

~Hannes



> I think when the values are positive everything is mostly great.  I think
> when the values are negative is where the main problems are.  Both the C
> function strncpy() and the C++ strings `substr()` function only support
> positive values for length AFAIK.
>
> I just think it is very unintuitive for the first parameter always to be a
> position, and the 2nd parameter to be a length if the value is positive,
> and
> a position if the value is negative.
>
> substr('string', 1, 2); // Goes from position 1 to position 3
> substr('string', -2, -1); // Goes from position -2 to position -1
>
> So here is the same kind of thing in python, which uses [start, end):
> string[1:2] ==> 't'
> string[-2:-1] ==> 'n'
>
> And ruby, which uses [start, end]:
> "string"[2..3] ==> 'tr'
> "string"[-2:-1] ==> 'ng'
>
> Both of these languages use positions for positive and negative values.  In
> addition, in both of these languages if you slice a string impossibly, both
> of them return an empy string as opposed to false, which just seems more
> intuitive to me.
>
> I don't think this function is particularly novel, I just think both
> returning an empty string on impossible slicing and slicing based on
> positions are improvements, and combined I think this function is
> noticeably
> more durable and readable than `substr()`.
>
> -Dan
>
> On Tue, Mar 29, 2011 at 11:22 PM, Lars Schultz <lars.schultz@toolpark.com
> > […]
>
> > […]
> before,
> > […]
> couldn't
> > […]
> a
> > […]
> string
> > […]
> but
> > […]
> offer
> > […]
> to
> > […]

---

## #51749 — Martin Scotta — 2011-03-30T14:02:53+00:00

URL: https://externals.io/message/51745#51749 · In reply to: #51748

IMHO substr is just fine enough. It does what you expect and behaves great
on edges cases.
What I believe is that we need more high-level string abstractions (and that
includes functions as well)

substr, strpos and the like works just fine to access strings by offsets,
but when you need to work with substrings the code gets really messy.

how do you test that a string starts with a string?
$string = 'string';
$start = 'str';

0 === strpos($string, $start); // to test that it starts
false === strpos($string, $start); // to test that it does not starts

yeah, it's not too complicated... but it's not legible at a glance, how does
it java?

String string = "string";
String str = "str";
string.startWith(str);

and, how do you test that a string ends with another string....

$str === substr($string, -1 * strlen($str));

tricky, isn't... how about Java?

string.endsWith(str);

I don't speak Ruby or Python... how do you do this in such languages?

 Martin Scotta


On Wed, Mar 30, 2011 at 10:05 AM, Hannes Landeholm <landeholm@gmail.com>wrote:

> PHP's `substr()` is awesome and that comes from a person that code in at
> least
> 5 different languages daily. Parsing is a problem in many real-world
> problems and substr currently works great for that purpose. You work with
> two parameters: offset and length of parsing. Since meaning of a negative
> offset/length when sub-stringing is intuitively undefined, PHP has reserved
> these ranges for two common usecases: offsets from the end of the string
> and
> truncation length.
>
> "I just think it is very unintuitive for the first parameter always to be a
> position, and the 2nd parameter to be a length if the value is positive,
> and
> a position if the value is negative."
>
> The first parameter is either an offset from start or offset from end - the
> second parameter is either a length or a truncation length. I don't see why
> this would be unintuitive? Perhaps you get confused by other languages that
> just work with offsets.
>
> In most real world parsing scenarios I've worked with offsets and lengths,
> so the current substr definition gets my job done fastest without doubt.
> Let's have a real world example "Parse through the data in chunks of 64
> bytes at a time." In PHP this is simple, just take the current offset and a
> length of 64. In python you'd have to add 64 to the current offset and put
> into the second offset parameter = you have to think more and write more
> code instead of just working with the length directly.
>
> "Returning `FALSE` when start + length parameters are invalid.  This is
> annoying
> because when using this function you always have to deal with this `FALSE` 
> case if
> you need a string. "
>
> Guess what this code outputs?
>
> var_dump((string) \substr("foo", 5, 6));
>
> Now try this and you'll understand why this is basically never a problem
> that substr outputs false and why you don't even have to think about it:
>
> var_dump(\substr("foo", 5, 6) == "", (string) false, false == "");
>
> Welcome to PHP. To be honest this criticism pretty much falls in the "from
> person that comes from another language X and is annoyed that every little
> detail isn't exactly the same"-category. Just make your own `substr()`
> function that uses the behavior you expect if you don't like the native
> version. Although that's bad practice - the best solution is to get used to
> it. And if you have an urge to write about your experience with a new
> language I suggest you do it in a blog instead of posting it in the
> internals mailing list...
>
> ~Hannes
>
> 
>
> > […]
> a
> > […]
>  In
> > […]
> both
> > […]
> lars.schultz@toolpark.com
> > […]
> as
> > […]
> do
> > […]
> adds
> > […]
> start,
> > […]
> around
> > […]
> the
> > […]
> with
> > […]

---

## #51750 — Josh Davis — 2011-03-30T14:08:56+00:00

URL: https://externals.io/message/51745#51750 · In reply to: #51748

> Parsing is a problem in many real-world
> problems and substr currently works great for that purpose.

That's funny because the first thing I thought when I read the
original mail was "oh that would be great for parsing." In fact, I've
just grep'ed through some code from a rich text parser I've been
working on and at first glance there are at ~5 occurences of `substr()`
that I would replace with str_slice(). There are also 15+ occurences
of `substr()` that would remain untouched. It's not black-and-white,
sometimes you want N characters starting from pos X, and other times
you want to cut the text from pos X and pos Y, and that's where
str_slice() would be welcome.

This thread shouldn't be a criticism of `substr()`, it would be
pointless. Its signature and behaviour will never change, unless
perhaps around April 1st as a practical joke on the millions of
websites it would break. The question is: is str_slice() useful, does
it fill a need and should it be included into PHP?

-JD

---

## #51751 — Hannes Landeholm — 2011-03-30T14:28:05+00:00

URL: https://externals.io/message/51745#51751 · In reply to: #51750

"This thread shouldn't be a criticism of `substr()`, it would be
pointless. Its signature and behaviour will never change, unless
perhaps around April 1st as a practical joke on the millions of
websites it would break."

That's a really good joke actually. I can imagine how angry people would
get. Maybe PHP could post it as a fake news update tomorrow?

And yeah, I wouldn't mind an extra string slicing function although I think
substr is sufficient... and if you're adding extra string functions there
are more useful ones. These are the string functions in my PHP framework
that I use regularly:

// Already mentioned:
starts_with($subject, $prefix) // returns bool
ends_with($subject, $tail) // returns bool
// Generating codes/ids:
random_str($length = 16) // returns any string
random_hex_str($length = 16) // returns any 0-9a-f
random_alphanum_str($length = 16, $case_sensitive = true) // returns any
a-z0-9/A-Z0-9
from_index($index) // 0 returns a, 1 returns b .. 3 => c..  n => z.. n + 1
=> aa..  n + 2 => ab...
// like base64 but only uses 0-9a-z (it encodes / as ad, + as ac and a as
ab)
base64_alphanum_encode($data)
base64_alphanum_decode($str)
// hex encodes string (eg. "\x11\x1c" => "111c")
hex_encode($str)
hex_decode($str)
email_validate($email) // regex email validation (the actual regex is 390
characters and has never failed me... don't ask me how it works though)
http_url_validate($url)
in_range($string, $min = -1, $max = -1) // returns true if string has a
certain length (easier to read and faster to write)
quote($string) // for exporting any string to javascript escaping any escape
or control characters automatically (e.g. \n) so "foo\"bar" becomes exactly
that

~Hannes




> 
> > […]
>
> That's funny because the first thing I thought when I read the
> original mail was "oh that would be great for parsing." In fact, I've
> just grep'ed through some code from a rich text parser I've been
> working on and at first glance there are at ~5 occurences of `substr()`
> that I would replace with str_slice(). There are also 15+ occurences
> of `substr()` that would remain untouched. It's not black-and-white,
> sometimes you want N characters starting from pos X, and other times
> you want to cut the text from pos X and pos Y, and that's where
> str_slice() would be welcome.
>
> This thread shouldn't be a criticism of `substr()`, it would be
> pointless. Its signature and behaviour will never change, unless
> perhaps around April 1st as a practical joke on the millions of
> websites it would break. The question is: is str_slice() useful, does
> it fill a need and should it be included into PHP?
>
> -JD

---

## #51752 — Jonathan Bond-Caron — 2011-03-30T14:43:54+00:00

URL: https://externals.io/message/51745#51752 · In reply to: #51748

> 
> var_dump(\substr("foo", 5, 6) == "", (string) false, false == "");
> 
> Welcome to PHP. To be honest this criticism pretty much falls in the 
> "from person that comes from another language X and is annoyed that 
> every little detail isn't exactly the same"-category. Just make your 
> own `substr()` function that uses the behavior you expect if you don't 
> like the native version. Although that's bad practice - the best 
> solution is to get used to it. And if you have an urge to write about 
> your experience with a new language I suggest you do it in a blog 
> instead of posting it in the internals mailing list...

I agree with what you're saying but I think you're being a little harsh,
experience with a new language should be something that matters to
internals.

Back to Dan, you're hitting type conversion so not sure I understand "you
always have to deal with this `FALSE` case":

var_dump(substr('', -1) == '0'); // `TRUE` 
var_dump(substr('', -1) === '0'); // `FALSE` 

Equally to Dan, it doesn't seem like a great way to start the conversation
by saying the "interface is inconsistent and confusing".
There's a perception issue here since you're already used to using language
X,Y,Z.

That said the patch seems to add value to php, why not add str_slice() if it
can solve consistency issues for some users? str_slice likely could be a
faster alternative to `substr()` in userland parsers. 

Also I've seen plenty of bugs caused by type conversion & `substr()` in
userland

---

## #51753 — Chad Fulton — 2011-03-30T15:54:41+00:00

URL: https://externals.io/message/51745#51753 · In reply to: #51752

Hello!

While I personally like PHP's `substr()` an awful lot and doubt I would
use the str_slice() method, I thought I'd mention that I think what
you're proposing is much like the string.substring(from, to) method in
Javascript (and PHP's current `substr()` function is an awful lot like
Javascript's string.substr(start, end) method).

With that in mind, if this function was to be implemented, I think
that naming it substring() instead of str_slice() might make it easier
for people to pick up out of the box, since PHP developers often have
quite a bit of overlap with Javascript.

Chad

---

## #51754 — Reindl Harald — 2011-03-30T16:00:25+00:00

URL: https://externals.io/message/51745#51754 · In reply to: #51753

Am 30.03.2011 17:54, schrieb Chad Fulton:
> While I personally like PHP's `substr()` an awful lot
> 
> With that in mind, if this function was to be implemented, I think
> that naming it substring() instead of str_slice() might make it easier
> for people to pick up out of the box, since PHP developers often have
> quite a bit of overlap with Javascript

a really bad idea!

after that you have `substr()` and substring() and we should avoid doing
things like "mysql_escape_string" and "mysql_real_escap_string" again

---

## #51755 — Dan Birken — 2011-03-30T19:36:55+00:00

URL: https://externals.io/message/51745#51755 · In reply to: #51752

The example I picked in my patch was a little contrived, however I do think
it is a useful benefit for functions to work in ways people expect, even in
edge cases.  There are a lot of people out there who do not know the
difference between == and ===, and I think the fact that str_slice() has one
less potential bug to worry about is a tangible improvement.

As for adding other string functions, I agree, I think there are a lot of
them that would be great to add.  starts_with & ends_with for sure.  I just
didn't want to write a really large patch for a whole host of functions
before having the discussion about this one.

I also don't mean to attack PHP.  I think the interface for this function is
heavily borrowed from C, and I think because PHP has different goals than C
(ease of use being one of them), that improvements can be made from this
perspective.  I think from a functionality point of view for an expert user,
the C function interfaces are great.

-Dan

On Wed, Mar 30, 2011 at 7:43 AM, Jonathan Bond-Caron <jbondc@openmv.com>wrote:

> 
> > […]
>
> I agree with what you're saying but I think you're being a little harsh,
> experience with a new language should be something that matters to
> internals.
>
> Back to Dan, you're hitting type conversion so not sure I understand "you
> always have to deal with this `FALSE` case":
>
> var_dump(substr('', -1) == '0'); // `TRUE` 
> var_dump(substr('', -1) === '0'); // `FALSE` 
>
> Equally to Dan, it doesn't seem like a great way to start the conversation
> by saying the "interface is inconsistent and confusing".
> There's a perception issue here since you're already used to using language
> X,Y,Z.
>
> That said the patch seems to add value to php, why not add str_slice() if
> it
> can solve consistency issues for some users? str_slice likely could be a
> faster alternative to `substr()` in userland parsers.
>
> Also I've seen plenty of bugs caused by type conversion & `substr()` in
> userland

---

## #51756 — Martin Jansen — 2011-03-30T19:42:54+00:00

URL: https://externals.io/message/51745#51756 · In reply to: #51755

> As for adding other string functions, I agree, I think there are a lot of
> them that would be great to add.  starts_with & ends_with for sure.

Both str_startswith and str_endswith have been suggested in the past:

http://marc.info/?t=121647230100001&r=1&w=2

I recently got around to merge them into a largely unfinished extension
so they are archived somewhere safe: https://github.com/mj/php-ext-str

- Martin

---

## #51757 — Jevon Wright — 2011-03-30T22:35:41+00:00

URL: https://externals.io/message/51745#51757 · In reply to: #51745

If `substr()` really was so bad, then surely we'd see userland
implementations of str_slice() in every project?

Jevon


> My apologizes if I am bringing up a topic that has been discussed before,
> this is my first time wading into the PHP developers lists and I couldn't
> find anything particularly relevant with the search.
>
> Here is a bug I submitted over the weekend (
> http://bugs.php.net/bug.php?id=54387) with an attached patch that adds a
> str_slice() function into PHP.  This function is just a very simple string
> slicing function, with the logical interface of str_slice(string, start,
> [end]).  It is of course meant to replace `substr()` as an interface for
> string slicing.
>
> I detailed the reasons I submitted the patch in the bug a little bit, but
> the main reason is that I think the `substr()` function is really overly
> confusing and just not an intuitive method of string slicing, which is
> exceedingly common functionality.  I realize we don't want to go around
> adding lots of random little functions into the language that don't offer
> much, but the problem with that is that if we have a function like `substr()`
> with an unusual and unintuitive interface, it becomes unchangeable due to
> legacy issues and then you can never improve.  I think this particular
> functionality is important enough to offer an updated interface.  In the bug
> I also pointed to two related bugs that would be essentially fixed with this
> patch.
>
> -Dan

---

## #51758 — Dan Birken — 2011-03-30T23:29:20+00:00

URL: https://externals.io/message/51745#51758 · In reply to: #51757

I think most users of a language take what they are given for basic
functions like this instead of always rolling their own.  I admit that both
of the changes I am suggesting here are minor, but taken together I do think
it is a significant and tangible difference (and improvement).  I think if
you are going by the metric of people rolling their own, then the functions
"starts_with" and "ends_with" have probably been implemented many many times
by people in various projects (see
http://stackoverflow.com/questions/834303/php-startswith-and-endswith-functions,
especially notice the solutions using strrev or regex searching).  However
in that previous discuss that Martin linked to, it looks like it was show
down because the functions were deemed too trivial.  A funny sidenote is
that this message (http://marc.info/?l=php-internals&m=121667513510896&w=2)
in that previous discussion has the exact bug in it which I mentioned in my
bug (if (substr($path, -strlen($extension)) == $extension) is `TRUE` for $path
= '' and $extension = '0').

I guess the core of my argument is the current PHP string functions, which
certainly provide all functionality one could want, are not optimized from
simplicity or user friendliness.  If PHP wants to optimize for the
conciseness of the core library, than I understand an argument to keep out
functions like this.  However, if PHP wants to add in functions that are
simpler to use and have more user friendly interfaces, I think it would
benefit by adding in a few of the functions mentioned here (slice,
ends_with, starts_with).  The reason I led with str_slice, is because I
think str_slice makes ends_with and starts_with trivial with no potential
corner cases, so if I could pick one function to add, I would pick
str_slice.

-Dan



> If `substr()` really was so bad, then surely we'd see userland
> implementations of str_slice() in every project?
>
> Jevon
>
> 
> > […]
> string
> > […]
> `substr()`
> > […]
> bug
> > […]
> this
> > […]

---

## #51764 — Philip Olson — 2011-03-31T14:41:02+00:00

URL: https://externals.io/message/51745#51764 · In reply to: #51756

> 
> > […]
> 
> Both str_startswith and str_endswith have been suggested in the past:
> 
> http://marc.info/?t=121647230100001&r=1&w=2
> 
> I recently got around to merge them into a largely unfinished extension
> so they are archived somewhere safe: https://github.com/mj/php-ext-str

I see `str_contains()` on the TODO there. I've always wanted in_string() so am glad to see a similar item. Using `strpos()` for this task feels dirty, much like using arrpos() for arrays would ;)

Regards,
Philip

---

## #51765 — Martin Jansen — 2011-03-31T14:49:50+00:00

URL: https://externals.io/message/51745#51765 · In reply to: #51764

> 
> > […]
> 
> I see `str_contains()` on the TODO there. I've always wanted in_string() so am glad to see a similar item. Using `strpos()` for this task feels dirty, much like using arrpos() for arrays would ;)

>From time to time I have wondered if it made sense to add a new operator
"in" that works on variables of different type and could replace
in_string/str_contains:

if ("a" in "abc") { ... }

if ("a" in array("a", "b", "c")) { ... }

if ("a" in $obj) { /* true if $obj->__contains("a") returned true */ }

I suspect there is a massive potential for WTF issues in there and that
most people would hate this feature.  Which is why I am only thinking
out loud here -- I have zero intentions to suggest this as a future
enhancement for PHP.  ;-)

- Martin

---

## #51766 — Ferenc Kovacs — 2011-03-31T14:52:40+00:00

URL: https://externals.io/message/51745#51766 · In reply to: #51765

> 
> > […]
> am glad to see a similar item. Using `strpos()` for this task feels dirty,
> much like using arrpos() for arrays would ;)
>
> > […]
> "in" that works on variables of different type and could replace
> in_string/str_contains:
>
> if ("a" in "abc") { ... }
>
> if ("a" in array("a", "b", "c")) { ... }
>
> if ("a" in $obj) { /* true if $obj->__contains("a") returned true */ }
>
> I suspect there is a massive potential for WTF issues in there and that
> most people would hate this feature.  Which is why I am only thinking
> out loud here -- I have zero intentions to suggest this as a future
> enhancement for PHP.  ;-)
>
> - Martin
>
> --
> 
> 
>
>
would we have mb_in also? :)

Tyrael

---

## #51767 — Rasmus Lerdorf — 2011-03-31T15:05:49+00:00

URL: https://externals.io/message/51745#51767 · In reply to: #51764

> 
> 
> 
> > […]
> 
> I see `str_contains()` on the TODO there. I've always wanted in_string() so am glad to see a similar item. Using `strpos()` for this task feels dirty, much like using arrpos() for arrays would ;)

How would `str_contains()` be different from `strstr()`?

-Rasmus

---

## #51768 — Martin Scotta — 2011-03-31T15:36:48+00:00

URL: https://externals.io/message/51745#51768 · In reply to: #51767

Martin Scotta




> 
> > […]
> of
> > […]
> am glad to see a similar item. Using `strpos()` for this task feels dirty,
> much like using arrpos() for arrays would ;)
>
> How would `str_contains()` be different from `strstr()`?
>
>
They differ in the return type

boolean str_contains(string, string);
string strstr(string, string);



-Rasmus

---

## #51769 — Brian Moon — 2011-03-31T15:43:13+00:00

URL: https://externals.io/message/51745#51769 · In reply to: #51768

> > […]
> They differ in the return type

$instr = (bool)strstr($string1, $string2);

done. No need for a new function.

Brian.

---

## #51770 — Martin Jansen — 2011-03-31T15:44:27+00:00

URL: https://externals.io/message/51745#51770 · In reply to: #51767

> 
> > […]
> 
> How would `str_contains()` be different from `strstr()`?

I think my main objective was to have a utility function that has the
advantages of strpos (i.e. faster and less memory usage than strstr)
while having a strict boolean return value so that I don't need to
remember to use === all the time.

- Martin

---

## #51771 — Philip Olson — 2011-03-31T15:45:52+00:00

URL: https://externals.io/message/51745#51771 · In reply to: #51769

> > […]
> 
> $instr = (bool)strstr($string1, $string2);
> 
> done. No need for a new function.

Well, to be clearer:

bool str_contains( haystack, needle [, case_insensitive = false ] )
string str[i]str( haystack, needle [, $before_needle = false ] )

The main differences:
- Return value is a bool
- No ordinal value conversions (I assume)
- No === usage worries/requirements
- Intuitive name

Regards,
Philip

---

## #51772 — Rasmus Lerdorf — 2011-03-31T15:52:48+00:00

URL: https://externals.io/message/51745#51772 · In reply to: #51771

> - Intuitive name

Argh! Everyone should be forced to learn a bit of C. Like many PHP
functions, the name and argument order is right out of libc. If you type
"man strstr" at your (non-Windows) prompt you get a nice little
description of what it does.

-Rasmus

---

## #51773 — Sebastian Bergmann — 2011-03-31T15:55:55+00:00

URL: https://externals.io/message/51745#51773 · In reply to: #51772

Am 31.03.2011 17:52, schrieb Rasmus Lerdorf:
> Argh! Everyone should be forced to learn a bit of C. Like many PHP
> functions, the name and argument order is right out of libc. If you type
> "man strstr" at your (non-Windows) prompt you get a nice little
> description of what it does.

 And if you install pman you just do "pman strstr" and get PHP-specific
 documentation.

-- 
Sebastian Bergmann                    Co-Founder and Principal Consultant
http://sebastian-bergmann.de/                           http://thePHP.cc/

---

## #51774 — Peter Cowburn — 2011-03-31T16:19:32+00:00

URL: https://externals.io/message/51745#51774 · In reply to: #51769

> > […]
>
> $instr = (bool)strstr($string1, $string2);
>
> done. No need for a new function.

God forbid anyone use (bool)strstr("something0", "0") !

>
> Brian.

---

Next page: https://externals.io/message/51745.md?page=2
