Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split the string which containing underscore, dash and space [duplicate]

Tags:

string

regex

php

I have a string like

$str = "hyper text-markup_language";
$keywords = preg_split("/[_,-, ]+/", $str);

i used preg_split, but it split the string on the basis of underscore and dash not on the basis on space.

i want result like this

[0] = hyper
[1] = text
[2] = markup
[3] = language
like image 267
user3056158 Avatar asked Jan 29 '26 02:01

user3056158


2 Answers

Nice and simple solution.

<?php
$str = "hyper text-markup_language";
$arr = preg_split("/[_,\- ]+/", $str);
var_dump($arr);
?>

This produces this output.

array (size=4)
  0 => string 'hyper' (length=5)
  1 => string 'text' (length=4)
  2 => string 'markup' (length=6)
  3 => string 'language' (length=8)

The issue was when you were writing the - character, the RegEx was reading this as a range value from the comma to the comma (which obviously is just a comma).

Escaping the hyphen and removing the duplicate comma (the square brackets mean list of anything inside) will produce an array.

RegEx explained

Square brackets are referred to as Character Sets.
They will match anything that is in them. See this example.

/gr[ae]y/

This will match gray and grey. This is because the square brackets are matching the a or the e. Changing the above to /gr[a-e]y/ would mean that gray, grby, grcy, grdy, and grey would all match. This is because the hyphen (-) is a special character that will create a list from what is before the the hyphen to what is after it.

An alternative (following @anubhava comment) is to put the hyphen at the beginning or end of the character set in order for it to not need escaping since there it cannot create a range if there is nothing in front or behind it.

like image 60
JustCarty Avatar answered Jan 31 '26 14:01

JustCarty


@user3056158 you can also do it without preg_split() like below :

<?php
  $str = "hyper text-markup_language";
  $str = str_replace(array(" ", "-", "_"), " ", $str);
  echo "<pre>";
  print_r(explode(" ", $str));
?>
like image 42
Vishal Solanki Avatar answered Jan 31 '26 14:01

Vishal Solanki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!