The idea is to grab values from the following string.
String: Server has [cpu]4[cpu] cores and [ram]16gb[ram]
I need to grab the tags value and what is between the tag dynamically: should not matter what is between [*]*[*]
Output: Should be an array as follows
Array(
'cpu' => 4,
'ram' => '16gb'
)
Having a lot of trouble with the regex pattern. Any help would be appreciated.
EDIT: the value between tags or the tags themselves can be anything - Alphanumeric or Numeric.
The sample string is a sample only. Tags can appear unlimited times and the array therefore needs to be populated on the fly - not manually.
Custom HTML tags are new tags that you name yourself in HTML to create new elements. Custom tags must contain a hyphen (-), start with an ASCII character (a-z), and be all lowercase for them to be valid. Custom elements make HTML simple to code, easier to read and keep your CSS well organized.
Let’s see how! Open your Google Tag Manager account. Then open one of the conversion Tags through which you want to send the value data. Scroll down to the Conversion Value field and click on the brick beside the value box to select the Data Layer variable. Next, click on Continue.
Within the HTML spec, it is valid to create your own HTML tags, these are called custom elements and they must follow a strict naming convention for them to be valid. Custom elements must have an opening and a corresponding closing tag. Self-closing custom elements are not valid HTML. What Are Custom HTML Tags?
Custom tags must contain a hyphen (-), start with an ASCII character (a-z), and be all lowercase for them to be valid. Custom elements make HTML simple to code, easier to read and keep your CSS well organized. Custom HTML elements must start with an ASCII character (a-z), contain at least one hyphen (-), and never contain any capital letters.
My PHP is rusty, but maybe:
$str = "Server has [cpu]4[cpu] cores and [ram]16gb[ram] and [memory]2tb[/memory]";
$matches = array();
preg_match_all('/\[(\w+)\]([^\[\]]+)\[\/?\w+\]/', $str, $matches);
$output = array_combine($matches[1], $matches[2]);
Details:
[
or ]
can appear in []
as the tag.[
or ]
can be the value of the tag$string = '[cpu]4[cpu] cores and [ram]16gb[ram]';
preg_match('|\[([^\]]+)\]([^\[]+)\[/?[^\]]+\][^\[]+\[([^\]]+)\]([^\[]+)\[/?[^\]]+\]|', $string, $matches);
$array = array($matches[1] => $matches[2], $matches[3] => $matches[4]);
print_r($array);
Others can build upon my code or suggest me in doing something better:
<pre><?php
$string = "Server has [cpu]4[cpu] cores and [ram]16gb[ram] and [memory]2tb[/memory]";
$matches = array();
$pattern = '/\[(\w+)\]([^\[\]]+)\[\/?\w+\]/';
preg_match_all($pattern, $string, $matches);
$output = array_combine($matches[1], $matches[2]);
var_dump($output);
?></pre>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With