Reputation: 327
I'm trying to define a regex in php to extract words but i didn't succeed... My string is always in this format: "toto=on test=on azerty=on gogo=on" what I would like to do is to get in an array the values toto, test,azerty and gogo. Can someone help ?
that's what i tried so far : /([^\s]|[w]*?=)/
Upvotes: 1
Views: 67
Reputation: 58
It's simple
preg_match_all("/(\w*)=/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
It will get all word before "=", the parentheses is for defining a group and put in key "1" , "\w" is for a letter and "*" is for "many"
or You can improve that and use like that
preg_match_all("/(\w*)=on/", "toto=on test=on azerty=on gogo=on", $output_array)[1];
So will get only parameters "on", if you have "toto=on test=on azerty=on gogo=on toff=off", the string "toff" dont will appear
I like to use this link http://www.phpliveregex.com/ , so you can try regex and responses in PHP
Upvotes: 2
Reputation: 1787
You can juse use explode()
:
$str = 'toto=on test=on azerty=on gogo=on';
$words = array_map(function($item){ return substr($item, 0, -3); }, explode(' ', $str));
Upvotes: 1
Reputation: 1367
A different approach to this question would be this way
<?php
$str = "toto=on test=on azerty=on gogo=on";
$res = str_replace("=on","", $str);
$array = explode(" ", $res);
print_r($array); //Array ( [0] => toto [1] => test [2] => azerty [3] => gogo )
?>
Upvotes: 2
Reputation: 12382
Sure! Here's a working regex: https://regex101.com/r/IWP1Mh/1
And here's the working code: https://3v4l.org/QQZj5
<?php
$regex = '#(?<names>\w*)=\w*#';
$string = 'toto=on test=on azerty=on gogo=on';
preg_match_all($regex, $string, $matches);
$names = $matches['names'];
var_dump($names);
Which outputs:
array(4) {
[0]=> string(4) "toto"
[1]=> string(4) "test"
[2]=> string(6) "azerty"
[3]=> string(4) "gogo"
}
Upvotes: 1