4

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.

Gjert
  • 1,069
  • 1
  • 18
  • 48

2 Answers2

1

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

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • And this works even if the user registers with unique letters such as chinese, æøåöäë and has numbers in the username? – Gjert Jun 10 '15 at 09:47
  • I used this: `$msg_all_receivers = $_POST['receiver']; preg_match_all('~\b\w+(?=\)>)~', $msg_all_receivers, $msg_all_receivers_exp);` and echoed with this: `echo $msg_all_receivers_exp[0].$msg_all_receivers_exp[1];` However, I get the error message: `Notice: Undefined offset: 1 in /home/connecti/www/projects/send_message.php on line 328` followed by `Array` – Gjert Jun 10 '15 at 09:51
  • You have to use: `echo $msg_all_receivers_exp[0][0].$msg_all_receivers_exp[0][1];` Also see updated answer for unicode support. – anubhava Jun 10 '15 at 09:52
  • Ah, okai, thank you. Does count() work on the underlaying array? or will it just count 1? – Gjert Jun 10 '15 at 09:53
  • So I would do `$count = count($m[0])`? – Gjert Jun 10 '15 at 09:55
1

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]);
Saty
  • 22,443
  • 7
  • 33
  • 51