简体   繁体   中英

Best way to divide the string from specific character | PHP

Sorry! This question may be similar but not a duplicate ...

Suppose I have strings of different sizes as follows:

zinc tab. 25mg №60
vita sip bla b6 50% b6mg №7
5-nok tab. 50mg №50
Blah blah №50

In short, I need the result should be as follows:

$str1 = "zinc tab"; $str2 = "25mg №60";
$str1 = "vita sip bla b6"; $str2 = "50% b6mg №7";
$str1 = "5-nok tab."; $str2 = "50mg №50";
$str1 = "Blah blah"; $str2 = "№50";

The allocated value starts with a number. That is, the number starting from the last part need to be divided into two. I tried with implode() , explode() , preg_split() , preg_match() functions. But they are broken down into several parts with a certain precision. For example:

$str = 'Bla bla 50% 400mg №4';
$results = preg_split('/[^0-9]/', $str);
print_r($results);
// Also i got same result with explode, implode functions...

//Then also tried with substr functions like that
$str[strlen($string) -2];

//But string indices are not always the same.

I've also worked with substr() functions, but the string index not always the same. Sometimes it can come in third or second place from the last. I need the result as follows: If any word at the end of the text begins with a number or begins with №, it should be divided into two at this point. Like that:

4 bla bla 40% 50mg №50 should return: 1) 4 bla bla 2) 40% 50mg №50
4 bla bla №50 should resturn 1) 4 bla bla, 2) №50

How is it easy and fast to get such a result? Thanks!

This is nowhere what I would call a robust regex.
But it clears the test.

It tries to find the delimiting "words" and which seems to be number-letter or №-number or number-percent

preg_match_all("/(.*?)\s([\d|№]+[a-zA-Z%0-9]{1}.*)/", $str, $m);

https://3v4l.org/cSXec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM