12

I have the following code:

explode("delimiter", $snippet);

But I want that my delimiter is case-insensitive.

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Luis Liz
  • 1,939
  • 4
  • 20
  • 31

3 Answers3

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().

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Michael Robinson
  • 29,278
  • 12
  • 104
  • 130
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));
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.

John
  • 1
  • 13
  • 98
  • 177
  • 3
    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. – Dr. Chocolate May 23 '17 at 14:22
  • @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! – John May 26 '20 at 07:21
  • @John 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. – user6096790 Oct 09 '22 at 04:07
  • The array return will lose the original case of the string. – Anuj Shrestha Apr 12 '23 at 06:09