how do i get ALL the value inside the parenthesis? - php

i need to get all the string/content inside each parenthesis inside of a string.
example: $string = "hello (cool) how are you (i am okay) where are you from (i am from earth)"; i am using preg_match_all like this preg_match_all('#\((.*?)\)#', $nonumber, $match); and then once i get the content of whatever is inside the parenthesis i want to put it in array
so i want each content inside parenthesis and put it into array like this.
the first array will have the value of cool
the second one will have value of i am okay
i tried to echo $match[0] but i get error Array to string conversion.
to put it simply i want the value to be inside an array. like this
$match[0] will have value of cool
$match[1] will have value of i am okay
and so on
like an array that you can call the value
i am desperate and dont know how to fix this. please help

You are on the right track to use preg_match_all, but you should use the pattern \((.*?)\):
$regexp = "/\((.*?)\)/";
$string = "hello (cool) how are you (i am okay) where are you from (i am from earth)";
preg_match_all($regexp, $string, $matches);
foreach ($matches[1] as $value) {
echo $value . "\n";
}
cool
i am okay
i am from earth
Demo

Related

PHP preg_replace string with value of variable

I am trying to use regex in php to find all strings that starts with "$" and replacing it with the appropriate variable. For example:
$value = "Some Value";
<b>$value</b>
Where the end result should be:
<b>Some Value</b>
This is what I have tried:
ob_start("tagreplace");
function tagreplace ( $tagreplace )
{
$value1 = "Some Value";
$pattern = '/(?<=\s)(\$[^#\s]+)(?=\s)/';
$tagreplace = preg_replace( $pattern , '<?php echo $0 ?>', $tagreplace);
return $tagreplace;
}
/* html files for combining */
include 'main_content.html';
ob_end_flush();
But this doesn't seem to work... I've tried for loops, while loops, and none of them are working. Basically I am trying to be extremely lazy and use regex to make very shorthand variables that I can put everywhere, replacing the strings like "$value" with whatever corresponding value that the variable $value has assigned to it.
I understand that /e is now deprecated so I can't use that to treat php tags as actual code. I have attempted to use preg_replace_callback but this didn't actually do anything. I'm thinking there probably isn't a way to properly do this.
It's not exactly clear what you're trying to do here, although if you take a slightly different approach with your regex you'll likely have more success. Essentially it's easier to break the pattern up into three capture groups (the start tag, the value, and the end tag)
function tagreplace ( $tagreplace ) {
$replace = "Some Value";
$pattern = '/(.+>)(.+)(<.+)/m';
$tagreplace = preg_replace( $pattern, '$1'.$replace.'$3', $tagreplace);
return $tagreplace;
}
$value = "Old Value";
echo tagreplace("<b>$value</b>");
echo "\n -- Using \$value slightly different-- \n";
$value = "<b>$value</b>";
echo tagreplace($value);
By using a more generic pattern you should be able swap out $value, regardless if it's the entire value, or if it's what is between the < > tags. When in doubt use a regex tester (linked below) and you might be able to eliminate several recursive loops, or going around in circles.
Example:
https://regex101.com/r/rW8lC6/1

preg_match acting very strange

I am using preg_match() to extract pieces of text from a variable, and let's say the variable looks like this:
[htmlcode]This is supposed to be displayed[/htmlcode]
middle text
[htmlcode]This is also supposed to be displayed[/htmlcode]
i want to extract the contents of the [htmlcode]'s and input them into an array. i am doing this by using preg_match().
preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}
The above code outputs
[htmlcode]This is supposed to be displayed[/htmlcode]middle text[htmlcode]This is also supposed to be displayed[/htmlcode]
instead of
[htmlcode]This is supposed to be displayed[/htmlcode]
[htmlcode]This is also supposed to be displayed[/htmlcode]
and if have offically run out of ideas
As explained already; the * pattern is greedy. Another thing is to use preg_match_all() function. It'll return you a multi-dimension array of matched content.
preg_match_all('#\[htmlcode\]([^\"]*?)\[/htmlcode\]#ms', $text, $matches);
foreach( $matches[1] as $value ) {
And you'll get this: http://codepad.viper-7.com/z2GuSd
A * grouper is greedy, i.e. it will eat everything until last [/htmlcode]. Try replacing * with non-greedy *?.
* is by default greedy, ([^\"]*?) (notice the added ?) should make it lazy.
What do lazy and greedy mean in the context of regular expressions?
Look at this piece of code:
preg_match('/\[htmlcode\]([^\"]*)\[\/htmlcode\]/ms', $text, $matches);
foreach($matches as $value){
return $value . "<br />";
}
Now, if your pattern works fine and all is ok, you should know:
return statement will break all loops and will exit the function.
The first element in matches is the whole match, the whole string. In your case $text
So, what you did is returned the first big string and exited the function.
I suggest you can check for desired results:
$matches[1] and $matches[2]

Locate text in string in PHP

I have a string of varying length taken from a MySQL database and in that string is a value (in bold below):
s:1:"4", s:2:"53", s:3:"7", s:4:"5"
I need a way to find whatever is in quotes following the s:3:. So in this example, it would be 7. I've looked around and I think I need to use the explode function but I am having trouble implementing it. The string may contain multiple values of this in which case I'd like to get them all into an array.
Use preg_match_all() for that:
$str = 's:1:"4", s:2:"53", s:3:"7", s:4:"5"';
if(preg_match_all('/s:3:"(.*?)"/', $str, $matches)) {
var_dump($matches[1]);
}
Non-greedy method, includes multi-lines.
<?php
$str = 's:1:"4", s:2:"53", s:3:"7", s:4:"5"';
if(preg_match_all('!s:3:"([^"]+)"!s', $str, $matches)) {
print_r($matches);
}
?>

How to search for a pattern like [num:0] and replace it?

I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10

preg_math multiply responce

<?php
$string = "Movies and Stars I., 32. part";
$pattern = "((IX|IV|V?I{0,3}[\.]))";
if(preg_match($pattern, $string, $x) == false)
{
print "NAPAKA!";
}
else
{
print_r($x);
}
?>
And the response is:
Array ( [0] => I. [1] => I. )
I should get only 1 response... Why do I get multiple responses?
The element at index 0 is the whole matched string. The element at index 1 is the contents of the first capture group, i.e. the content inside the parenthesis. In this case, they just happen to be the same. Just use $x[0] to get the value you're looking for.
The nested parenthesis should, in this instance, be a "non-capturing" subpattern.
$pattern = "~((?:IX|IV|V?I{0,3}[\.]))~";
Try that. It will tell the regex compiler to not capture the results of those parenthesis into the array.
In fact, looking at your regex, you don't even need those parenthesis. Make your regex this:
$pattern = "~IX|IV|V?I{0,3}[\.]~";
That should also work.
Your pattern has multiple groups in it -> the () brackets tell you what to capture in your match.
Try this:
$pattern = "(IX|IV|V?I{0,3}[\.])";
If you have a hard time identifying the wanted groups in the result you can name them as specified in the php.net documentation.
That would look something like this:
$pattern = "(?P<groupname>IX|IV|V?I{0,3}[\.])";
You get 0-indexed for all mathced string and result for every paretness (). it's helpful to get groups i.e
preg_match('~([0-9]+)([a-z]+)','12abc',$x);
$x is ([0]=>12abc [1]=>12 [2]=>abc)
In your case you can simply delete () (1 pair ot them, 1 pair is used as delimiters)

Categories