Exploding and trimming a long string effectively resulting in a single array

77 views Asked by At

I'm trying to create a messaging system where you can send to a single or multiple users at the same time. The value which is delivered from my form looks like this:

<Username One(1)><Username Two(2)><Username Three(3)>

Now, in order for me to post the messages to the database I want to explode and trim this information into three seperate parts. All of which is inside an array.

I want the output to be something like this:

Array[0] = 1
Array[1] = 2
Array[2] = 3

I've tried using explode(">", $input_value); and then use preg_matchto trim. However, I end up with two seperate arrays. How can I combine these two and get the result I want? I need it to be as effective as possible as each user should be able to message maximum amount of users at the same time. Also I would appreciate an easy to understand explanation of regex as I find it a bit confusing.

2

There are 2 answers

5
anubhava On BEST ANSWER

You can use:

$s = '<Username One(1)><Username Two(2)><Username Three(3)>';    
preg_match_all('~\b[\p{L}\p{N}]+(?=\h*\)>)~u', $s, $m);    
print_r($m[0]);

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

(?=\h*\)>) is a positive lookahead that matches word before )>

1
Saty On

Since 1,2,3 are digit in your string. so you can get all the digit from your string

<?php
$str="<Username One(1)><Username Two(2)><Username Three(3)>";
preg_match_all('!\d+!', $str, $matches);
print_r($matches[0]);

Second thing all string between () brackets

preg_match_all("/\((.*?)\)/", $str, $matches);

print_r($matches[0]);