Regex to match {#layout=xxx} - php

I am trying to learn the behinds of template system by creating my own and I have hit a bump...
I want to setup my template as follows:
{#layout=layoutname}
{#content}
<p>This is a paragraph</p>
{#endcontent}
But I don't know how to match {#layout= and get the layout name.
I have tried: if (preg_match('/(\{\#layout=[a-z]+\})+/', $string, $matches)) { which works ... kind of. I want to check if there are more then 1 layouts loaded to prevent errors in long files and want to count how many $matches I have and return error if more then 1 match is found but instead of getting all found layouts, it returns the same layout twice:
String used:
{#layout=app}
{#layout=main}
{#content}
<h1>{[username]} profile</h1>
<img src="{[photoURL]}" class="photo" alt="{[name]}" width="100" height="100"/>
<b>Name:</b> {[name]}<br />
<b>Age:</b> {[age]}<br />
<b>Location:</b> {[location]}<br />
{#endcontent}
and using that expression I get:
Array ( [0] => {#layout=app} [1] => {#layout=app} )
can someone please help me find my regex?

You need to use preg_match_all to get multiple matches in the same string. In this case, you want to check the $matches[1] which will be an array of capture group results. If you have more than one layout, it will have more than one element so if that's the case you know there is more than one layout declaration.
I would also change your regex to /\{\#layout=([a-z]+)\}/ which will capture only the layout name. $matches will look like:
array(2) {
[0]=>
array(1) {
[0]=>
string(20) "{#layout=layoutname}"
}
[1]=>
array(1) {
[0]=>
string(10) "layoutname"
}
}
So if count($matches[1]) > 1, you know there is more than one layout declaration. Otherwise, $matches[1][0] is your layout name.

Thanks to #SebastianProske I have found what I was looking for:
if (preg_match_all('/\{\#layout=([a-zA-Z0-9]+)*\}/', $string, $matches)) {
that is the correct if, that returns also the name and all the matches.
Thank you for your time,
Ares D.

Related

How to get text in array between all <span> tag from HTML?

I want to fetch text in array between all <span> </span> tag from HTML, I have tried with this code but it returns only one occurrence :
preg_match('/<span>(.+?)<\/span>/is', $row['tbl_highlighted_icon_content'], $matches);
echo $matches[1];
My HTML:
<span>The wish to</span> be unfairly treated is a compromise attempt that would COMBINE attack <span>and innocen</span>ce. Who can combine the wholly incompatible, and make a unity of what can NEVER j<span>oin? Walk </span>you the gentle way,
My code returns only one occurrence of span tag, but I want get all text from every span tag in HTML in the form of a php array.
you need to switch to preg_match_all function
Code
$row['tbl_highlighted_icon_content'] = '<span>The wish to</span> be unfairly treated is a compromise attempt that would COMBINE attack <span>and innocen</span>ce. Who can combine the wholly incompatible, and make a unity of what can NEVER j<span>oin? Walk </span>you the gentle way,';
preg_match_all('/<span>.*?<\/span>/is', $row['tbl_highlighted_icon_content'], $matches);
var_dump($matches);
as you can see now array is correctly populated so you can echo all your matches
use preg_match_all() it's the same, it will return all the occurrences in the $matches array
http://php.net/manual/en/function.preg-match-all.php
here is code to get all span value in array
$str = "<span>The wish to</span> be unfairly treated is a compromise
attempt that would COMBINE attack <span>and innocen</span>ce.
Who can combine the wholly incompatible, and make a unity
of what can NEVER j<span>oin? Walk </span>you the gentle way,";
preg_match_all("/<span>(.+?)<\/span>/is", $str, $matches);
echo "<pre>";
print_r($matches);
you output will be
Array
(
[0] => Array
(
[0] => The wish to
[1] => and innocen
[2] => oin? Walk
)
[1] => Array
(
[0] => The wish to
[1] => and innocen
[2] => oin? Walk
)
)
you can use o or 1 index
If you don't mind using a third-party component, I'd like to show you Symfony's DomCrawler component. It 's a very simple way to parse HTML/XHTML/XML files and navigate through the nodes.
You can even use CSS Selectors. Your code would be something like:
$crawler = new Crawler($html);
$spans = $crawler->filter("span");
echo $spans[1]->getText();;
You don't even need to have a full HTML/XML document, if you assign only the <span>...</span> part of your code, it'll work fine.

PHP - strpos if it contains anything inside [ ]

I have the following which works great, but now what I want to do is if a user types [MAP] then I want to get the word MAP
I also want allow users to send things like [MAP = array("LOCATION"=>"Melbourne Australia")]
and for the PHP to make map a array so I can then send it to a function later on
I currently do the following
$map = strpos($stringtocheck, "[MAP]");
But the issue here, is if we have a number of [] with different insides like [BOLD], [INSERT] etc then it wont find it and put it in its own $
and also it means we need to know what the array is field with or anything like that
A simple regex will pull info out of square brackets:
$s = 'Yo be [diggin] [my leet] scriptzors!';
$matches = null;
preg_match_all('/\[(.*?)\]/', $s, $matches);
var_dump($matches[1]);
Result:
array(2) {
[0]=>
string(6) "diggin"
[1]=>
string(7) "my leet"
}
Example: http://codepad.viper-7.com/erBpuB

PHPquery lib. and parsing XML

I started using the phpquery thingy, but I got lost in all that documentation.
In case someone does not know what the hell I am talking about: http://code.google.com/p/phpquery/
My question is pretty much basic.
I succeeded at loading an XML document and now I want to parse all the tags from it.
Using pq()->find('title') I can output all of the contents inside the title tags. Great!
But I want to throw every <title> tag in a variable. So, lets say that there are 10 <title> tags, I want every one of them in a separate variable, like: $title1, $title2 ... $title10. How can this be done?
Hope you understand the question.
TIA!
You could do it like this:
phpQuery::unloadDocuments();
phpQuery::newDocument($content);
$allTitles = [];
pq('title')->each(function ($item) use (&$allTitles) {
$allTitles[] = pq($item)->text();
});
var_dump($allTitles);
For example if there are 3 titles in the $content this var_dump will output:
array(3) {
[0] =>
string(6) "title1"
[1] =>
string(6) "title2"
[2] =>
string(6) "title3"
}

PHP Simple CSS string parser

I need to parse some CSS code like:
color: black;
font-family:"Courier New";
background:url('test.png');
color: red;
--crap;
Into:
array (
'color'=>'red',
'font-family'=>'"Courier New"',
'background'=>'url(\'test.png\')',
'--crap'=>''
)
I need to do this via PHP. I can see this done easily via regexp (well, easy to those that know it, unlike myself :-) ).
I need the resulting array to be "normalized", there should not be any trailing spaces between tokens, even if they were in the source.
Valueless css tokens should be included in the array as a key only. (see --crap)
Quotes (and values in general) should remain as is, except for extra formatting (spaces, tabs); easily removed via trim() or via the relevant regexp switch.
Please not that at this point, I specifically do not need a full CSS parser, ie, there is no need to parse blocks ( {...} ) or selectors ( a.myclass#myid ).
Oh, and considering I'll be putting this stuff in an array, it is perfectly ok if the last items ( color:red; ) completely override the original items ( color:black; ).
Here's a simple version:
$a = array();
preg_match_all('/^\s*([^:]+)(:\s*(.+))?;\s*$/m', $css, $matches, PREG_SET_ORDER);
foreach ($matches as $match)
$a[$match[1]] = isset($match[3]) ? $match[3] : null;
Sample output:
array(4) {
["color"]=>
string(3) "red"
["font-family"]=>
string(13) ""Courier New""
["background"]=>
string(15) "url('test.png')"
["--crap"]=>
NULL
}
Not tested with anything except your source data, so I'm sure it has flaws. Might be enough to get you started.
I found this few weeks back and looks interesting.
http://websvn.atrc.utoronto.ca/wsvn/filedetails.php?repname=atutor&path=/trunk/docs/include/classes/cssparser.php
Example:
$Parser = new cssparser();
$Results = $Parser->ParseStr("color: black;font-family:"CourierNew";background:url('test.png');color: red;--crap;");
Why don't take a look at CSSTidy?
You can try:
$result = array();
if(preg_match_all('/\s*([-\w]+)\s*:?\s*(.*?)\s*;/m',$input,$m))
var_dump($m);
// $m[1] contains all the properties
// $m[2] contains their respective values.
for($i=0;$i<count($m[1]);$i++) {
$result[$m[1][$i]] = $m[2][$i];
}
}

PHP: Strange Array Problem - Where is my value?

I have an array ($form) which retreives some information from $_POST:
$form = $_POST['game'];
Now I want to work with the values in this array, but I somehow fail.
For debugging I used these commands (in the exact same order, with no extra lines inbetween):
print_r($form);
echo '#' . $form['System_ID'] . "#";
and as returned output I get:
Array
(
['Title'] => Empire: Total War - Special Forces
['Genre_ID'] => 1
['Type'] => Spiel
['System_ID'] => 1
)
##
Any ideas where my System_ID went? It's there in print_r, but not in the next line for echo?!?
Alright, I found the solution myself (a.k.a. d'oh!)
I added another
var_dump($form);
for further analysis and this is what I got:
array(4) {
["'Title'"]=>
string(34) "Empire: Total War - Special Forces"
["'Genre_ID'"]=>
string(1) "1"
["'Type'"]=>
string(5) "Spiel"
["'System_ID'"]=>
string(1) "1"
}
Notice the single quote inside the double quote?
Looks as if you're not allowed to use the single quote in html forms or they will be included in the array key:
Wrong: <input type="text" name="game['Title']" />
Correct: <input type="text" name="game[Title]" />
print_r() doesn't put quotes around keys - for debugging i'd recommend ditching print_r altogether. var_export or var_dump are better.
even better: use firephp. it sends the debug info via headers, so it doesn't mess up your output and thus is even usable with ajax. output is displayed nicely with firebug including syntax coloring for data structures.
and it's even easier to use: just fb($myvar);
It works for me:
<?
$form['System_ID'] = 1;
print_r($form);
echo '#' . $form['System_ID'] . '#';
?>
Output:
% php foo.php
Array
(
[System_ID] => 1
)
#1#
PHP 5.2.6, on Fedora Core 10
EDIT - note that there's a hint to the real cause here. In my code the print_r output (correctly) shows the array keys without single quotes around them. The original poster's keys did have quotes around them in the print_r output, showing that somehow the actual key contained the quote marks.

Categories