I use PHP, I want to check if there is a name attribute and if thats is an array or an array with multiple levels,for example:
name="hello"
name="hello[]"
name="hello[1]"
name="hello[1][2]"
etc
I want to get hello and the array after it seperated and returned in an array i think:
array(hello,'')
array(hello,[])
array(hello,[1])
array(hello,[1][2])
something like that, so I can glue them back together or use seperatly later on
I think it must be done with regular expressions but how ?
Split on:
(?<!\])(?=\[)
This would split on the first [ character before which no ] character is encountered. eg.
$keywords = preg_split("/(?<!\])(?=\[)/", "hello[1][2]");
print_r($keywords);
Output
Array
(
[0] => hello
[1] => [1][2]
)
Related
If I have a example string like this: "dataset1"=>"blank","gdataset"=>"f1,f2"
I'm trying to create an array of the key/value pairs.
Desired array result should look like this:
Array(
[0] => "dataset1"=>"blank"
[1] => "gdataset"=>"f1,f2"
)
I've tried http_build_query & explode w/o success, as the array key or value is getting mangled.
What should I use to get the desired array?
It's kind of hackish, but just replace "," with "","" to keep the quotes and then explode on ",":
$result = explode('","', str_replace('","', '"",""', $string));
But I'm positive that there is a much better way to do whatever you are doing in general. Maybe a new question outlining why you are doing this?
Given the following code :
$str = 'CLAX';
echo $str[2]; //prints 'A'
then why should I use str_split( $str ) to convert string to a array of characters ?
I understand str_split( $str , 2 ) will return array of strings; each string being 2 characters long.
http://php.net/manual/en/function.str-split.php
This function is to split a string into an array with given string split length
By default string split length is set 1
If you want to split a string into given in given length, then you can use str_split. But in your case you are splitting string with default length 1 that is by you are getting confused.
<?php
$str = "CLAX";
echo $str[2]; //here you are referring to 2 index of string
$arr2 = str_split($str);
Array
(
[0] => C
[1] => L
[2] => A
[3] => X
)
echo $str[2]; //here you are referring to 2 index of an array
str_split reference
<?php
$str = "Hello Friend";
$arr2 = str_split($str, 3);
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Using str_split() comes in pretty handy when you want to leverage array functions to perform a task on the components in a string.
str_split() works like explode() except it doesn't care what the characters are, just their position in the string -- there are specific use cases for this.
Use Case #1: Group Array Elements by Letter Range
Rather than manually declaring an array with 3 letters per element, like this:
$chunks=['ABC','DEF','GHI','JKL','MNO','PQR','STU','VWX','YZ']
The same array can be produced with:
$chunks=str_split(implode(range('A','Z')),3);
This purely for demonstration. Of course, declaring it manually would be more efficient. The potential benefit for other cases is code flexibility and ease of code modification.
Use Case #2: Convert string to array at different character occurence
Use str_split() when using a foreach loop to process each character.
$string="abbbaaaaaabbbb";
$array=str_split($string);
$last="";
foreach($array as $v){
if(!$last || strpos($last,$v)!==false){
$last.=$v;
}else{
$result[]=$last;
$last=$v;
}
}
$result[]=$last;
var_export($result);
If you try to supply the foreach loop with $string php will choke on it. str_split() is the right tool for this job.
Use Case #3: Find element of an array those contains only specific character set in PHP
Use str_split() to in association with other array functions to check values in a way that string functions are not well suited for.
[I'll refrain from transferring the full code block across.]
I need help to find out the strings from a text which starts with # and till the next immediate space by preg_match in php
Ex : I want to get #string from this line as separate.
In this example, I need to extract "#string" alone from this line.
Could any body help me to find out the solutions for this.
Thanks in advance!
PHP and Python are not the same in regard to searches. If you've already used a function like strip_tags on your capture, then something like this might work better than the Python example provided in one of the other answers since we can also use look-around assertions.
<?php
$string = <<<EOT
I want to get #string from this line as separate.
In this example, I need to extract "#string" alone from this line.
#maybe the username is at the front.
Or it could be at the end #whynot, right!
dog#cat.com would be an e-mail address and should not match.
EOT;
echo $string."<br>";
preg_match_all('~(?<=[\s])#[^\s.,!?]+~',$string,$matches);
print_r($matches);
?>
Output results
Array
(
[0] => Array
(
[0] => #string
[1] => #maybe
[2] => #whynot
)
)
Update
If you're pulling straight from the HTML stream itself, looking at the Twitter HTML it's formatted like this however:
<s>#</s><b>UserName</b>
So to match a username from the html stream you would match with the following:
<?php
$string = <<<EOT
<s>#</s><b>Nancy</b> what are you on about?
I want to get <s>#</s><b>string</b> from this line as separate. In this example, I need to extract "#string" alone from this line.
<s>#</s><b>maybe</b> the username is at the front.
Or it could be at the end <s>#</s><b>WhyNot</b>, right!
dog#cat.com would be an e-mail address and should not match.
EOT;
$matchpattern = '~(<s>(#)</s><b\>([^<]+)</b>)~';
preg_match_all($matchpattern,$string,$matches);
$users = array();
foreach ($matches[0] as $username){
$cleanUsername = strip_tags($username);
$users[]=$cleanUsername;
}
print_r($users);
Output
Array
(
[0] => #Nancy
[1] => #string
[2] => #maybe
[3] => #WhyNot
)
Just do simply:
preg_match('/#\S+/', $string, $matches);
The result is in $matches[0]
I'm trying to get the 2 values in this string using regex:
a:2:{i:45;s:29:"Program Name 1";i:590;s:19:"Program Name 2";}
There are 2 variables that start with "s:" and end with ":" which I am attempting to get from this string (and similar strings.
$string = 'a:2:{i:45;s:29:"Program Name 1";i:590;s:19:"Program Name 2";}';
preg_match_all("/s:(\d+):/si", $page['perfarray'], $match);
print_r($match);
I have tried numerous things but this is the first time I've attempted to use regex to get multiple values from a string.
This is the current result: Array ( [0] => Array ( ) [1] => Array ( ) )
Any constructive help is greatly appreciated. I have already read the functions on php.net and I can't find a similar question on stack overflow that matches my needs closely enough. Thanks in advance.
That looks like a serialized string. Instead of using a regular expression, use unserialize() to retrieve the required value.
Update: It looks like your string is not a valid serialized string. In that case, you can use a regular expression to get the job done:
$string = 'a:2:{i:45;s:29:"Program Name 1";i:590;s:19:"Program Name 2";}';
if(preg_match_all("/s:(\d+):/si", $string, $matches)) {
print_r($matches[1]);
}
Output:
Array
(
[0] => 29
[1] => 19
)
That should work:
preg_match_all("/s:([0-9]+):/si", $page['perfarray'], $match);
I have the following string
"Enter Contarct Fields wherever you want and enclose it with {}.You can use field's id or field's fieldcode for example {25} or {FIELD_CONTRACTTEXT}"
I want to replace this {25} and {FIELD_CONTRACTTEXT} with their equivalent value from databse.
Say 25 is a ID so I wanted to put name of the field of which 25 is the ID of.
There are many examples of replacing curly braces but no solution is there for replacing content like this. Please help me, I have tried many things.
PS: Please keep in mind that occurrence of {} is dynamic and 25 will not be a static number and there can be multiple {} in a string.
You can use preg_match_all() to find the occurrences, use this array to find the values in the database and then str_replace to replace each value after that.
To begin with you will need to fetch all the occurrences:
preg_match_all('/{(.*?)}/', $string, $matches, PREG_PATTERN_ORDER);
The matches array will look like this:
Array
(
[0] => Array
(
[0] => {}
[1] => {25}
[2] => {FIELD_CONTRACTTEXT}
)
[1] => Array
(
[0] =>
[1] => 25
[2] => FIELD_CONTRACTTEXT
)
)
You can then cylce through the array to find the individual elements that need to be replaced.
You can use the following to check the database and then replace values:
mysql_connect("localhost", "root", "");
mysql_select_db("data");
$string = "Enter Contarct Fields wherever you want and enclose it with {}.You can use field's id or field's fieldcode for example {25} or {FIELD_CONTRACTTEXT}";
preg_match_all('/{(.*?)}/', $string, $matches, PREG_PATTERN_ORDER);
foreach($matches[1] as $match) {
$sql = mysql_query("SELECT * FROM table WHERE `element`='".addslashes($match)."'");
if(mysql_num_rows($sql)==1){
$row = mysql_fetch_assoc($sql);
str_replace($string, "{".$match."}", $row['value']);
}
}
echo $string; //echos final output with replaced values