Seperate values from string in between characters in php - php

I have a string ("$big_string") in php with is combination of small section of strings("$string") like this one "-val1(sec1)-", for eg :
$string1="-val1(sec1)-";
$string2="-val2(sec2)-";
$string3="-val3(sec3)-";
$big_string=$string1.$string2.$string3;
How can I separate values from $big_string to an array-like
the val1.. and so on values are between '-' & '('
and the sec1... and so on values are beteen '(' & ')-'
$array[0][0]="val1";
$array[0][1]="sec1";
$array[1][0]="val2";
$array[1][1]="sec2";
$array[2][0]="val3";
$array[2][1]="sec3";
Edit: I received the $big_string as input, above code is for ref that how $big_string is constructed.

You could use preg_match_all:
$string1 = "-val1(sec1)-";
$string2 = "-val2(sec2)-";
$string3 = "-val3(sec3)-";
$big_string = $string1 . $string2 . $string3;
if (preg_match_all('/-([^(]+)\(([^)]+)\)-/', $big_string, $matches, PREG_SET_ORDER)) {
$result = array_map(static fn($match) => array_slice($match, 1), $matches);
print_r($result);
}
If you're using PHP < 7.4, the line with $result can be changed into this:
$result = array_map(static function ($match) {
return array_slice($match, 1);
}, $matches);
Demo

I like to keep my code simple, using basic PHP functions. Something like this:
$big_string = '-val1(sec1)--val2(sec2)--val3(sec3)-';
$val_sec_array = explode('--', trim($big_string, '-'));
foreach ($val_sec_array as $val_sec) {
$array[] = [strstr($val_sec, '(', TRUE),
trim(strstr($val_sec, '('), '()')];
}
print_r($array);
The first line uses trim() to trim off the excess '-' at the begin and end of the $big_string and then explodes the remaining string into an array on each '--' it encounters.
The foreach loop then takes that array and uses strstr to first get the section before the '(' from the string and then the section after the '('. The '(' and ')' are then trimmed off the latter section. The two values then form an array [ ... , ... ] and are stored in the main array.
This is funny, saying it like this makes it sound more complex than it really is. Just look in the manual how this works:
explode()
trim()
foreach
strstr()
arrays

Related

Creating a String from an Array in PHP

I'm trying to create a string out of several array values like so:
$input = array("1140", "1141", "1142", "1144", "1143", "1102");
$rand_keys = array_rand($input, 2);
$str = "$input[$rand_keys[0]], $input[$rand_keys[1]]";
However, in the third line, I get this error:
Unexpected '[' expecting ']'
I thought that by converting the array to a value I would be able to use it in my string. What am I doing wrong with my syntax?
If you just want to fix your code, simply adjust that one line to this line:
$str = $input[$rand_keys[0]] .', '. $input[$rand_keys[1]];
Here are a couple of other nicer solutions:
shuffle($input);
$str = $input[0] .', '. $input[1];
Or:
shuffle($input);
$str = implode(', ',array_slice($input,0,2));
When you want to expand more than simple variables inside strings you need to use complex (curly syntax). Link to manual. You need to scroll down a little in the manual. Your last line of code will look like this:
$str = "{$input[$rand_keys[0]]}, {$input[$rand_keys[1]]}";
But you could also use implode to achieve the same result.
$str = implode(', ', [$rand_keys[0], $rand_keys[1]]);
It's up to you.

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

In comma delimited string is it possible to say "exists" in php

In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);

regex split string at first line break

I would like to split a string at the first line break, instead of the first blank line
'/^(.*?)\r?\n\r?\n(.*)/s' (first blank line)
So for instance, if I have:
$str = '2099 test\nAre you sure you
want to continue\n some other string
here...';
match[1] = '2099 test'
match[2] = 'Are you sure you want to continue\n some other string here...'
preg_split() has a limit parameter you can take to your advantage. You could just simply do:
$lines = preg_split('/\r\n|\r|\n/', $str, 2);
<?php
$str = "2099 test\nAre you sure you want to continue\n some other string here...";
$match = explode("\n",$str, 2);
print_r($match);
?>
returns
Array
(
[0] => 2099 test
[1] => Are you sure you want to continue
some other string here...
)
explode's last parameter is the number of elements you want to split the string into.
Normally just remove on \r?\n:
'/^(.*?)\r?\n(.*)/s'
You can use preg_split as:
$arr = preg_split("/\r?\n/",$str,2);
See it on Ideone
First line break:
$match = preg_split('/\R/', $str, 2);
First blank line:
$match = preg_split('/\R\R/', $str, 2);
Handles all the various ways of doing line breaks.
Also there was a question about splitting on the 2nd line break. Here is my implementation (maybe not most efficient... also note it replaces some line breaks with PHP_EOL)
function split_at_nth_line_break($str, $n = 1) {
$match = preg_split('/\R/', $str, $n+1);
if (count($match) === $n+1) {
$rest = array_pop($match);
}
$match = array(implode(PHP_EOL, $match));
if (isset($rest)) {
$match[] = $rest;
}
return $match;
}
$match = split_at_nth_line_break($str, 2);
Maybe you don't even need to use regex's. To get just split lines, see:
What's the simplest way to return the first line of a multi-line string in Perl?

PHP: concatenation of multidimensional array elements

I want to concatenate one element of a multidimensional array with some strings.
<?
$string1 = 'dog';
$string2 = array
(
'farm' => array('big'=>'cow', 'small'=>'duck'),
'jungle' => array('big'=>'bear', 'small'=>'fox')
);
$string3 = 'cat';
$type = 'farm';
$size = 'big';
$string = "$string1 $string2[$type][$size] $string3";
echo($string);
?>
By using this syntax for $string, I get:
dog Array[big] cat
I would like not to use the alternate syntax
$string = $string1 . ' ' . $string2[$type][$size] . ' ' . $string3;
which works.
What's wrong with "$string1 $string2[$type][$size] $string3"?
Use the "complex syntax":
$string = "$string1 {$string2[$type][$size]} $string3";
PHP's variable parsing is quite simple. It will recognize one level array access, but not more level. By enclosing the expression in {} you explicitly state which part of the string is a variable.
See PHP - Variable parsing.
I'm not a fan of complex syntax, or variable parsing in strings. Normally I would use the "alternate" syntax you described. You could do this as well:
$string = implode(' ', array($string1, $string2[$type][$size], $string3));
Use this:
$string = "$string1 {$string2[$type][$size]} $string3";

Categories