PHP case-insensitive explode()
Asked Answered
S

3

12

I have the following code:

explode("delimiter", $snippet);

But I want that my delimiter is case-insensitive.

Strangles answered 1/10, 2012 at 1:9 Comment(0)
F
36

Just use preg_split() and pass the flag i for case-insensitivity:

$keywords = preg_split("/your delimiter/i", $text);

Also make sure your delimiter which you pass to preg_split() doesn't cotain any sepcial regex characters. Otherwise make sure you escape them properly or use preg_quote().

Foxing answered 1/10, 2012 at 1:11 Comment(2)
(the /i modifier tells preg_split to perform a case-insensitive search)Inefficacious
Yeah, I had to wait some time will I could tick it.Strangles
F
2

You can first replace the delimiter and then use explode as normal. This can be done as a fairly readable one liner like this:

explode($delimiter,str_ireplace($delimiter,$delimiter,$snippet));
Freiman answered 21/3, 2019 at 17:44 Comment(0)
A
0
explode('delimiter',strtolower($snippet));
  1. Never use expensive regular expressions when more CPU affordable functions are available.

  2. Never use double-quotes unless you explicitly have a use for mixing variables inside of strings.

Apoloniaapolune answered 15/5, 2017 at 7:50 Comment(4)
What if I'm exploding a SQL string and you just lowercased my table name? We need to lowercase the delimiter and leave the string untouched.Durra
@mutant_city Why would you be using uppercase or camelCase for databases, table and column names? Great practice is using ALL UPPERCASE for SQL specific commands & all lowercase for database, table and column names making code not only more readable though predictable. Predictability in code is important for when you need to update your code to meet stricter policies. Debugging SQL queries with errors is the only time I'd imagine exploding an SQL query (and I've never have had to do that) so I'm really curious what legitimate use case there would be and why. Strict policies lead to success!Apoloniaapolune
@Apoloniaapolune Database naming conventions vary and one who needs to perform a query may not have control over database schema. The real world is messy and there are all kinds of legitimate use-cases that arise that may be difficult to just imagine up front. In my case, I'm needing to get a count of result records for an unknown query before actually running the query and I want to parse the query to replace select field names with "select count(*) ". Hence I am here in SO finding good ideas.Threadgill
The array return will lose the original case of the string.Brandybrandyn

© 2022 - 2024 — McMap. All rights reserved.