Explode String in PHP - php

If I have a string "123x456x78", how could I explode it to return an array containing "123" as the first element and "456" as the second element? Basically, I want to take strings that are followed by "x" (which is why "78" should be thrown out). I've been messing around with regular expressions, but am having trouble.
Thanks!
EDIT: if the string were "123x456x78x" I would need three elements: "123", "456", "78". Basically, for each region following an "x", I need to record the string up until the next "x".

Loads of different ways, but here's a RegEx as you were trying that:
$str = "123x456x78";
preg_match_all("/(\d+)x/", $str, $matches);
var_dump($matches[1]);
Output:
array(2) { [0]=> string(3) "123" [1]=> string(3) "456" }

$arr = explode("x", "123x456x78");
and then
unset($arr[2]);
if you really can't stand that poor 78.

use explode
$string='123x456x78';
$res = explode('x', $string);
if(count($res) > 0) {
echo $res[0];
if(count($res) > 1) {
echo $res[1];
}
}

$var = "123x456x78";
$array = explode("x", $var);
array_pop($array);

To explode AND remove the last result:
$string='123x456x78'; // original string
$res = explode('x', $string); // resulting array, exploded by 'x'
$c = count($res) - 1; // last key #, since array starts at 0 subtract 1
unset($res[$c]); // unset that last value, leaving you with everything else but that.

While I'm all for regular expressions, in this case it might be easier to just use PHP's array functions...
$result=array_slice(explode('x',$yourstring),0,-1);
This should work because only the last element returned by explode won't be followed by an 'x'. Not sure if explode will add an empty string as the last element if it ends on 'x' though, you might have to test that...

Use this below code to explode. It works well!
<?php
$str='123x456x78';
$res=explode('x',$str);
unset($res[count($res)-1]); // remove last array element
print_r($res);
?>

Related

php regex to extract single parameter value from string

I'm working with a string containing parameters, separated by some special characters in PHP with preg_match
An example could be like this one, which has four parameters.
1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?
Each parameter name is followed by ?#?, and its value is right next to it, ending with ?#? (note: values can be strings or numbers, and even special characters)
I've probably overcomplicated my regex, which works in SOME cases, but not if I search for the last parameter in the string..
This example returns 2222 as the correct value (in group 1) for 2ndParm
(?:.*)2ndParm\?#\?(.*?)\?#\?(?=.)(.*)
but it fails if 2ndParm is the last one in the string as in the following example:
1stparm?#?1111?#?2ndParm?#?2222?#?
I'd also appreciate help in just returning one group with my result.. i havent been able to do so, but since I always get the one I'm interested in group 1, I can get it easily anyway.
Without regex:
$str ='1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?';
$keyval = explode('?#?', trim($str, '?#'));
$result = [];
foreach($keyval as $item) {
[$key, $result[$key]] = explode('?#?', $item);
}
print_r($result);
demo
You don't need to use a regex for everything, and you should have a serious talk with whoever invented this horrid format about the fact that JSON, YAML, TOML, XML, etc exist.
function bizarre_unserialize($in) {
$tmp = explode('?#?', $in);
$tmp = array_filter($tmp); // remove empty
$tmp = array_map(
function($a) { return explode('?#?', $a); },
$tmp
);
// rearrange to key-value
return array_combine(array_column($tmp, 0), array_column($tmp, 1));
}
$input = '1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?';
var_dump(
bizarre_unserialize($input)
);
Output:
array(4) {
["1stparm"]=>
string(4) "1111"
["2ndParm"]=>
string(4) "2222"
["3rdParm"]=>
string(4) "3333"
["4thparm"]=>
string(3) "444"
}
You can use
(?P<key>.+?)
\Q?#?\E
(?P<value>.+?)
\Q?#?\E
in verbose mode, see a demo on regex101.com.
The \Q...\E construct disables the ? and # "super-powers" (no need to escape them here).
In PHP this could be
<?php
$string = "1stparm?#?1111?#?2ndParm?#?2222?#?3rdParm?#?3333?#?4thparm?#?444?#?";
$regex = "~(?P<key>.+?)\Q?#?\E(?P<value>.+?)\Q?#?\E~";
preg_match_all($regex, $string, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match["key"] . " = " . $match["value"] . "\n";
}
?>
Which yields
1stparm = 1111
2ndParm = 2222
3rdParm = 3333
4thparm = 444
Or shorter:
$result = array_map(
function($x) {return array($x["key"] => $x["value"]);}, $matches);
print_r($result);

Pipe Delimited List with numbers into array PHP

In the database I'm working on there's a string like this
1-Test Response|9-DNC|
This can have up to 9 pipe delimited items.
What I'm looking for advice on is the best possible way to take this string and turn it into an array with the number as the key and the string as the value.
I really suck with Regex. Can someone point me in the right direction?
Since it's not your fault you have the DB structured this way, please accept my sincere condolences. It must be hell working with this. Meh.
Now, to the point. You do not need regex to work with this string. If you have a problem and you want to solve it with regex, you have two problems.
Instead, use explode().
$testString = "1-Test Response|9-DNC|";
$result = [];
$explodedByPipeString = explode("|", $testString);
foreach($explodedByPipeString as $k => $v)
{
$explodedByDashString = explode("-", $v);
if(is_numeric($explodedByDashString[0]))
{
$result[$explodedByDashString[0]] = $explodedByDashString[1];
}
}
var_dump($result);
This gives
array(2) {
[1]=>
string(13) "Test Response"
[9]=>
string(3) "DNC"
}
Here's how I went about it for anyone else wondering
$SurveyOptions = preg_match_all('/(\d+)-([^|]+)/',
$res['survey_response_digit_map'], $matches);
$finalArray = array_combine($matches[1], $matches[2]);
Pretty straight forward.
Assuming the delimters: - and | do not exist in the keys or values, here is another non-regex way to tackle the string:
Code: (Demo)
$string = '1-Test Response|9-DNC|';
$string = str_replace(['-', '|'], ['=', '&'], $string); // generates: 1=Test Response&9=DNC&
parse_str($string, $result);
var_export($result);
Output:
array (
1 => 'Test Response',
9 => 'DNC',
)

How to grab number after a word or symbol in PHP?

I want to grab a text with PHP just like for an example, There is a data "The apple=10" and I want to grab only the numbers from the data which looks exactly like that. I mean, the number's place would be after 'equals'.
and my problem is that the number from the source can be 2 or 3 characters or on the other word it is inconstant.
please help me to solve them :)
$string = "Apple=10 | Orange=3 | Banana=7";
$elements = explode("|", $string);
$values = array();
foreach($elements as $element)
{
$element = trim($element);
$val_array = explode("=", $element);
$values[$val_array[0]] = $val_array[1];
}
var_dump($values);
Output:
array(3) {
["Apple"]=> string(2) "10"
["Orange"]=> string(1) "3"
["Banana"]=> string(1) "7"
}
Hope thats how you need it :)
Well, php is a bit lazy about int conversion, so 12345blablabla can be converted to 12345:
$value = intval(substr($str, strpos($str, '=') + 1));
Of course, this is not the cleanest way but it is simple. If you want something cleaner, you could use a regexp:
preg_match ('#=([0-9]+)#', $str, $matches);
$value = intval($matches[1]) ;
Try the below code:
$givenString= "The apple=10";
$required_string = substr($givenString, strpos($givenString, "=") + 1);
echo "output = ".$required_string ; // output = 10
Using strpos() function, you can Find the position of the first occurrence of a substring in a string
and substr() function, Return part of a string.

Remove phrases from string

I have a string like this:
..., "test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>, ....
I am exploding everything by , , but problem is that i dont want to have value laike this
[0] => "test1#test1.com" <test1#test1.com> i need to remove the emails which are in those <..> brackets.
So the result should be like this [0] => test1#test1.com.
Any offers how to drop the second phrase?
You can make use of a function that has been especially tailored for such email address lists, for example imap_rfc822_parse_adrlist. Mapping it and extracting the information you need might do it already:
$list = ""test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>";
$adresses = array_map(function($entry) {
return sprintf('%s#%s', $val->mailbox, $val->host);
}, imap_rfc822_parse_adrlist($list, ""));
This has the benefit that it properly deals with the quoted printable text in front that you have - which done properly is non-trivial (really).
The simplest way here - use strip_tags function (see strip_tags description)
<?php
$str = '"test1#test1.com" <test1#test1.com>';
$str= preg_replace("(<.*>+)", "", $str);
print $str;
?>
Use Regular Expressions to replace anything between <...> for empty strings, then explode your modified string into an array.
You can explode your text into an array and the run a array_map with a function that cleans your text. Something like this:
function clean($t){
//Use regexp to replace desired text
return preg_replace('/<[^>]*>/', '', $t);
}
$text = '"test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>';
$a = explode(',', $text);
var_dump($a);
$b = array_map("clean", $a);
var_dump($b);
The easiest way is to use preg_match:
preg_match('(<.*>+)', $your_emails, $matches);
print_r($matches); // array of zero or more matches depending on input
if
$yourString='"test1#test1.com" <test1#test1.com>';
you can use:
$yourString=substr($yourString,1,strpos($yourString,'<')-3);
(edited)
It's a line of code:
array_map(function($a){ return trim($a, ' "'); }, explode(',', strip_tags($string)));
And the whole:
<?php
$string = <<<TK
"test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>
TK;
$result = array_map(
function($a){
return trim($a, ' "');
},
explode(',', strip_tags($string))
);
var_dump($result);
Output:
array(4) {
[0]=>
string(15) "test1#test1.com"
[1]=>
string(15) "test2#test2.com"
[2]=>
string(15) "test3#test3.com"
[3]=>
string(15) "test4#test4.com"
}

how can split the result set array to string in php

i need help. i was developed a page in smarty , i got a result set from a query and i need to change the result set to string and stored in text area
my query is given below
select val from test
my result set is print in var_dump in controller
{ [0]=> array(1) { ["val"]=> string(1) "c" } [1]=> array(1) { ["val"]=> string(3) "c++" } [2]=> array(1) { ["val"]=> string(4) "java" } [3]=> array(1) { ["val"]=> string(3) "PHP" } }
i need to change in to sting like c,c++,java,PHP
the changing function is preformed only controller
ple help me.. and thk adv
Use foreach for that. See more information here - http://php.net/manual/en/control-structures.foreach.php .
Example -
$array = Array("333", "222", "111");
foreach($array as $string) {
echo $string.'<br />';
}
Another solution would be to use implode.
See more information here - http://php.net/manual/en/function.implode.php and again a small example -
$array = Array("333", "222", "111");
$strings = implode(",", $array); // comma in first quotes are seperator, you can set it also to " " for a single space.
echo $strings; // In this case it will output 333,222,111 if you would set it to empty space then it would output 333 222 11
EDIT:
For writing in file you must use file functions.
Check this link - http://php.net/manual/en/function.file-put-contents.php
example -
// your file
$file = 'sample.txt';
$array = Array("333", "222", "111");
// Add all strings to $content.
foreach($array as $string) {
$content .= $string.'<br />';
}
// write everything in file
file_put_contents($file, $content);
Suggestion:
When you are writing SQL queries, I would suggest that you already now start learning to write them correctly, so they are easier to read.
For example, your query -
select val from test
Could be changed to -
SELECT `val` FROM `test`
which is alot easier to read and understand.
If You need to join all array with some delimeters, then use implode.
Example:
$arr = array("hi", "peter!", "how", "are", "you");
echo implode(" ", $arr) . "?";
//output
// hi peter! how are you?
If you want a string separated by commas, you must use the implode function
string implode ( string $glue , array $pieces )
glue: Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.
pieces:The array of strings to implode.
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
http://www.php.net/manual/en/function.implode.php
Example
$array = Array("333", "222", "111");
$string = explode(',', $array);
returns
"333,222,111"
if you want spaces:
$string = explode(' ', $array);
returns
"333 222 111"

Categories