i have this string ++++++1DESIGNRESULTSM25Fe415(Main)
and i have similar string about 2000 lines from which i want to split these..
[++++++] [1] [DESIGNRESULTS] [M25] [Fe415] [(Main)]
from the pattern only the 2nd 4h and 5th value changes
eg.. ++++++2DESIGNRESULTSM30Fe418(Main) etc..
what i actually want is:
Split the first value [++++++]
Split the value after 4 Character of [DESIGNRESULTS] so ill get this [M25]
Split the value before 4 Character of [(Main)] so ill get this [Fe415]
After all this done store the final chunk of piece in an array.
the similar output what i want is
Array ( [0] => 1 [1] => M25 [2] => Fe415 )
Please help me with this...
Thanks in advance :)
Your data split needs are a bit unclear. A regular expression that will get separate matches on each of the chunks you first specify:
(\++)(\d)(DESIGNRESULTS)(M\d\d)(Fe\d\d\d)(\(Main\))
If you only need the two you are asking for at the end, you can use
(\d)DESIGNRESULTS(M\d\d)(Fe\d\d\d)
You could also replace \d\d with \d+ if the number of digits is unknown.
However, based on your examples it looks like each string chunk is a consistent length. It would be even faster to use
array(
substr($string, 6, 1)
//...
)
How about this
$str = "++++++1DESIGNRESULTSM25Fe415(Main)";
$match = array();
preg_match("/^\+{0,}(\d)DESIGNRESULTS(\w{3})(\w{5})/",$str,$match);
array_shift($match);
print_r($match);
Related
I have a string
$descr = "Hello this is a test string";
What I am trying to do is to split the string and store each word which is separated using space into separate array index in PHP. Should I use
$myarray = preg_split("[\s]",$descr);
Expected outcome :
$myarray(1) : hello
$myarray(2) : this
$myarray(3) : is
$myarray(4) : a
$myarray(5) : test
$myarray(6) : string
Each number denotes array index
$descr = "Hello this is a test string";
$myarray = explode(' ', $descr);
Will produce:
Array
(
[0] => Hello
[1] => this
[2] => is
[3] => a
[4] => test
[5] => string
)
Use the explode function which takes the delimiter as the first parameter and the string variable you want to "explode" as the second parameter. Each word separated by the sent delimiter will be an element in the array.
You need to use explode() like below:-
$myarray = explode(' ', $descr);
print_r($myarray);
Output:-https://eval.in/847916
To re-index and lowercase each word in your array do like this:-
<?php
$descr = "Hello this is a test string";
$myarray = explode(' ', $descr);
$myarray = array_map('strtolower',array_combine(range(1, count($myarray)), array_values($myarray)));
print_r($myarray);
Output:-https://eval.in/847960
To get how many elements are there in the array:-
echo count($myarray);
One of the best way is to use str_word_count
print_r(str_word_count($descr , 1));
This question is seeking support for a task comprised from 3 separate procedures.
How to split a string on spaces to generate an array of words? (The OP has a suboptimal, yet working solution for this part.)
Because the pattern is only seeking out "spaces" between words, the pattern could be changed to / /. This eliminates the check for additional white-space characters beyond just the space.
Better/Faster than a regex-based solutions would be to split the string using string functions.
explode(' ',$descr) would be the most popular and intuitive function call.
str_word_count($descr,1) as Ravi Hirani pointed out will also work, but is less intuitive.A major benefit to this function is that it seamlessly omits punctuation --
for instance, if the the OP's sample string had a period at the end, this function would omit it from the array!Furthermore, it is important to note what is considered a "word":
For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters.
How to generate an indexed array with keys starting from 1?
Bind a generated "keys" array (from 1) to a "values" array:
$words=explode(' ',$descr); array_combine(range(1,count($words)),$words)
Add a temporary value to the front of the indexed array ([0]), then remove the element with a function that preserves the array keys.
array_unshift($descr,''); unset($descr[0]);
array_unshift($descr,''); $descr=array_slice($descr,1,NULL,true);
How to convert a string to all lowercase? (it was hard to find a duplicate -- this a RTM question)
lcfirst($descr) will work in the OP's test case because only the first letter of the first word is capitalized.
strtolower($descr) is a more reliable choice as it changes whole strings to lowercase.
mb_strtolower($descr) if character encoding is relevant.
Note: ucwords() exists, but lcwords() does not.
There are so many paths to a correct result for this question. How do you determine which is the "best" one? Top priority should be Accuracy. Next should be Efficiency/Directness. Followed by some consideration for Readability. Code Brevity is a matter of personal choice and can clash with Readability.
With these considerations in mind, I would recommend these two methods:
Method #1: (one-liner, 3-functions, no new variables)
$descr="Hello this is a test string";
var_export(array_slice(explode(' ',' '.strtolower($descr)),1,null,true));
Method #2: (two-liner, 3-functions, one new variable)
$descr="Hello this is a test string";
$array=explode(' ',' '.strtolower($descr));
unset($array[0]);
var_export($array);
Method #2 should perform faster than #1 because unset() is a "lighter" function than array_slice().
Explanation for #1 : Convert the full input string to lowercase and prepend $descr with a blank space. The blank space will cause explode() to generate an extra empty element at the start of the output array. array_slice() will output generated array starting from the first element (omitting the unwanted first element).
Explanation for #2 : The same as #1 except it purges the first element from generated array using unset(). While this is faster, it must be written on its own line.
Output from either of my methods:
array (
1 => 'hello',
2 => 'this',
3 => 'is',
4 => 'a',
5 => 'test',
6 => 'string',
)
Related / Near-duplicate:
php explode and force array keys to start from 1 and not 0
I have a lot of strings like:
"1248, 60906068, 4536576, 858687( some text 67, 43, 45)"
And I want to check if the string starts from number and there are brackets in string, in same time I want to get all numbers from the begining to the first bracket. So for this example string result should be like:
[0] => 1248 , [1] => 60906068, [2] => 4536576, [3] => 858687
The point is that in the string after first number at the beginning of the string could be zero additional numbers or one number or even a lot of numbers.
I tried something like that:
^(\d+)(?:,\s?(\d+)?)*\([^\)]+\)$
But it takes only first and last number before brackets.
Is it possible to get all these numbers with only one Regular Expression?
Thank you in advance!
You can use this regex: (\d+)(?:\([^\)]+\))?
All numbers will be captured in Group 1.
See example.
Result:
1248
60906068
4536576
858687
I want to get the string between "yes""yes"
eg.
yes1231yesyes4567yes
output:
1231,4567
How to do it in php?
may be there are 1 more output '' between yesyes right?
In this particular example, you could use preg_match_all() with a regex to capture digits between "yes" and "yes":
preg_match_all("/yes(\d+)yes/", $your_string, $output_array);
print_r($output_array[1]);
// Array
// (
// [0] => 1231
// [1] => 4567
// )
And to achieve your desired output:
echo implode(',', $output_array[1]); // 1231,4567
Edit: side reference, if you need a looser match that will simply match all sets of numbers in a string e.g. in your comment 9yes123yes12, use the regex: (\d+) and it will match 9, 123 and 12.
Good Evening,
If you are referring to extracting the digits (as shown in your example) then you can achieve this by referencing the response of Christopher who answered a very similar question on this topic:
PHP code to remove everything but numbers
However, on the other hand, if you are looking to extract all instances of the word "yes" from the string, I would recommend using the str_replace method supplied by PHP.
Here is an example that would get you started;
str_replace("yes", "", "yes I do like cream on my eggs");
I trust that this information is of use.
This regex finds the right string, but only returns the first result. How do I make it search the rest of the text?
$text =",415.2109,520.33970,495.274100,482.3238,741.5634
655.3444,488.29980,741.5634";
preg_match("/[^,]+[\d+][.?][\d+]*/",$text,$data);
echo $data;
Follow up:
I'm pushing the initial expectations of this script, and I'm at the point where I'm pulling out more verbose data. Wasted many hours with this...can anyone shed some light?
heres my string:
155.101.153.123:simple:mass_mid:[479.0807,99.011, 100.876],mass_tol:[30],mass_mode: [1],adducts:[M+CH3OH+H],
130.216.138.250:simple:mass_mid:[290.13465,222.34566],mass_tol:[30],mass_mode:[1],adducts:[M+Na],
and heres my regex:
"/mass_mid:[((?:\d+)(?:.)(?:\d+)(?:,)*)/"
I'm really banging my head on this one! Can someone tell me how to exclude the line mass_mid:[ from the results, and keep the comma seperated values?
Use preg_match_all rather than preg_match
From the PHP Manual:
(`preg_match_all`) searches subject for all matches to the regular expression given in pattern and puts them in matches in the order specified by flags.
After the first match is found, the subsequent searches are continued on from end of the last match.
http://php.net/manual/en/function.preg-match-all.php
Don't use a regex. Use split to split apart your inputs on the commas.
Regexes are not a magic wand you wave at every problem that happens to involve strings.
Description
To extract a list of numeric values which may include a single decimal point, then you could use this regex
\d*\.?\d+
PHP Code Example:
<?php
$sourcestring=",415.2109,520.33970,495.274100,482.3238,741.5634
655.3444,488.29980,741.5634";
preg_match_all('/\d*\.?\d+/im',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
yields matches
$matches Array:
(
[0] => Array
(
[0] => 415.2109
[1] => 520.33970
[2] => 495.274100
[3] => 482.3238
[4] => 741.5634
[5] => 655.3444
[6] => 488.29980
[7] => 741.5634
)
)
I want to split a string into two parts, the string is almost free text,
for example:
$string = 'hi how are you';
and I want the split to look like this:
array(
[0] => hi
[1] => how are you
)
I tried using this regex: /(\S*)\s*(\.*)/ but even when the array returned is the correct size, the values comes empty.
What should be the pattern necessary to make this works?
What are the requirements? Your example seems pretty arbitrary. If all you want is to split on the first space and leave the rest of the string alone, this would do it, using explode:
$pieces = explode(' ', 'hi how are you', 2);
Which basically says "split on spaces and limit the resulting array to 2 elements"
You should not be escaping the "." in the last group. You're trying to match any character, not a literal period.
Corrected: /(\S*)\s*(.*)/