preg_replace regex not working as expected - php

So i'm trying to do the following and it's not working. not sure why:
$block = preg_replace('#\{([A-Z0-9\-_]+)\}#', "<?php " . $this->compile_var(\\1) . " ?>", $block);
What i'm using that for is to turn this input:
<link href="{VAR_TEMPLATE_PATH}css/common.css" rel="stylesheet" type="text/css">
into:
<link href="<?php $this->page_vars["TEMPLATE_PATH"] ?>css/common.css" rel="stylesheet" type="text/css">
The actual conversion is fine, thats all contained in compile_var, but preg_replace is no longer turning \\1 into "VAR_TEMPLATE_PATH", which is used to do when inside a string.
Instead it is passing "\1" as the argument for compile_var?
Why is this happening all of a sudden? and how can i fix it?
Cheers!

Use it like this:
$block = '<link href="{VAR_TEMPLATE_PATH}css/common.css" rel="stylesheet" type="text/css">';
$block=preg_replace('#\{(?:VAR_)?([\w-]+)\}#', '<?php $this->compile_var("\1") ?>', $block);
echo $block;
OUTPUT:
<link href="<?php $this->compile_var("TEMPLATE_PATH") ?>css/common.css" rel="stylesheet" type="text/css">
If you want VAR_ also in final output then use:
$block = preg_replace('#\{([\w-]+)\}#', '<?php $this->compile_var("\1") ?>', $block);

Try using \1 in compile_var instead.
<?php " . $this->compile_var(\1) . " ?>
Here's a working example: http://regex101.com/r/rM0jD1

Related

If statement to call custom stylesheet

I am looking for a way to use an If statement to call a certain custom style
something like
if ( is_page('page-id') ) {
"line to call stylesheet2.css";
}
Any ideas?
This should work for you:
if(is_page('page-id')){
echo '<link rel="stylesheet" type="text/css" href="my.css">';
}else {
echo '<link rel="stylesheet" type="text/css" href="another.css">';
}

Concatenate css with php in link meta stylesheet

What is the way to concatenate multiple css files into one line with php?
I want to reduce the following ..
<link href="reset.css" rel="stylesheet" type="text/css" media="screen">
<link href="grid.css" rel="stylesheet" type="text/css" media="screen">
<link href="commons.css" rel="stylesheet" type="text/css" media="screen">
into
<link href="concatenator.php+reset.css+grid.css+commons.css" rel="stylesheet" type="text/css" media="screen">
the result one css or html file with all stylesheet inside
This method reduce the http requests, and have other features for designer and developer with use dinamyc sites configurations.
The code posted by MatRt is close, but is using + signs instead of . signs for the appending and it doesn't seem to actually send the CSS to the page, even though it will print the CSS.
I managed to get the code supplied here working with a small tweak to it. Here it is:
<?php
// Check the parameter and stop if there is no files param
if (empty($_GET['files']))
die();
// Retrieve the list of files
$files = explode(",", $_GET['files']);
$directoryOfCss = 'C:\xampplite\htdocs\path\to\my\folder\css\\';
$cssContent = "";
// Loop on all potential file and try to retrieve its content
foreach($files as $oneFile)
{
//echo $directoryOfCss . $oneFile . ".css";
if (file_exists($directoryOfCss . $oneFile . ".css")){
//echo $directoryOfCss . $oneFile . ".css<br>";
$cssContent .= file_get_contents($directoryOfCss . $oneFile . ".css");
}
}
// Finally echo the total content of CSS
header("Content-Type: text/css");
header("X-Content-Type-Options: nosniff");
header("Content-Type: text/css;X-Content-Type-Options: nosniff;");
echo $cssContent;
I got the headers part from this post.
Your URL should be more like
concatenator.php?files=reset,grid,commons
Note: you can chose other separator if you don't like the ,
And the famous concatenator.php could be like
<?php
// Check the parameter and stop if there is no files param
if (empty($_GET['files']))
die();
// Retrieve the list of files
$files = explode(",", $_GET['files']);
$directoryOfCss = "/absolute/path/to/your/css/files/";
$cssContent = "";
// Loop on all potential file and try to retrieve its content
foreach($files as $oneFile)
{
if (file_exists($directoryOfCss + $oneFile + ".css"))
$cssContent += file_get_contents($directoryOfCss + $oneFile + ".css");
}
// Finally echo the total content of CSS
echo $cssContent;

Can't properly echo code with PHP

I'm trying to set up a conditional system which programatically detects both the browser (using the USER_AGENT string) and the platform (using PHP-Mobile-Detect). My current setup looks roughly like this:
<DOCTYPE html>
<html>
<head>
<?php
include("Mobile_Detect.php");
$detect = new Mobile_Detect();
?>
<?php if($detect->isiPad()) {
echo '<link rel="stylesheet" href="/style/iPad.css" type="text/css">';
}
else
{
echo '<meta charset="UTF-8">
<link rel="stylesheet" href="/style.css" type="text/css">;
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false)
{
echo '<link rel="stylesheet" href="../style/splash-webkit.css" type="text/css">';
}
//and so on for other browsers
[etc]'
}
The obvious problem that occurs here, is the conflict between the 's. The echo under else, rather than ending at the end of my <style> tag, as I would want it to, ends at the first ' to appear in the code, which, as it were, is in the first USER_AGENT declaration.
How can I bypass this issue?
You missed a ' at the end of this line:
<link rel="stylesheet" href="/style.css" type="text/css">;
Replace it with:
<link rel="stylesheet" href="/style.css" type="text/css">';
You are using single and double quotes nicely though. However, if you do need to use the same quotes, you can always escape them with a \. For example, this would also work:
echo '<meta charset=\'UTF-8\'>';
Try this and let me know then
else
{
echo '<meta charset="UTF-8"><link rel="stylesheet" href="/style.css" type="text/css">';
if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false)
{
echo '<link rel="stylesheet" href="../style/splash-webkit.css" type="text/css">';
}
//and so on for other browser
}

How to swap stylesheets with a link

I am developing a site using PHP, XHTML strict, and jQuery that will be flexible to support both mobile and desktop devices, using the Responsive Web Design approach and serving different stylesheets using the min-device-width property.
<link rel="stylesheet" href="css/960.css" type="text/css" media="screen and (min-device-width: 480px)" />
But the site will need to have a link to toggle the "desktop" and "moblie" view. I have a basic idea of how this could be done using jQuery, but would prefer a solution in php for devices that don't support JavaScript.
PHP isn't too hard to implement this with. If you were to use a link, like so...
Desktop view
Then in your page script...
//test for stylesheet parameter
if(isset($_GET['view']))
{
//save and set it in the session
$stylesheet = $_GET['view'];
$_SESSION['stylesheet'] = $stylesheet;
}
elseif(isset($_SESSION['stylesheet']))
{
//parameter not sent, so get it from the session
$stylesheet = $_SESSION['stylesheet'];
}
Later, you select your stylesheet code based on this $stylesheet variable.
if($stylesheet == 'desktop')
{
echo '<link rel="stylesheet" href="/css/desktop.css" type="text/css" />';
}
elseif($stylesheet == 'mobile')
{
echo '<link rel="stylesheet" href="/css/mobile.css" type="text/css" />';
}
else
{
echo'<link rel="stylesheet" href="css/960.css" type="text/css" media="screen and (min-device-width: 480px)" />';
}
You could use a SESSION variable for that. The following example assumes there are two stylesheets mobile.css and desktop.css
Testing the argument, and setting up the session.
<?php
session_start();
if(isset($_GET['style']))//Tests the argument
{
if($_GET['style']=="desktop")//This to prevent passing wrong arguments
{
$_SESSION['style']=$_GET['style'];
}
if($_GET['style']=="mobile")//This to prevent passing wrong arguments
{
$_SESSION['style']=$_GET['style'];
}
}
?>
<head>
blah
<?php
if(isset($_SESSION['style'])
{
echo '<link rel="stylesheet" href="'.$_SESSION['style'].'.css" type="text/css" media="all" />';
}
?>
</head>
Your link to switch from/to desktop CSS.
Desktop version
Mobile version
Well, why not just include the appropriate stylesheet depending on a query parameter, or session variable or UA etc etc
//Code that figures out what type is
$css = '';
switch ($type) {
case 'mobile':
$css = '<link rel="stylesheet" href="css/960.css" type="text/css" />';
break;
case 'touch':
$css = '<link rel="stylesheet" href="css/960-mobile.css" type="text/css" />';
break;
case 'desktop':
default:
$css = '<link rel="stylesheet" href="css/960-full.css" type="text/css" />';
break;
}
In your view
echo $css;
NOTE This is only an example. Ideally you shouldn't be constructing your whole link html in PHP, but not knowing any of your implementation details, it will suffice. Best way to do it would be to name your CSS files in a standard manner with only a -type at the end to differentiate where each file is used and just pass the $type variable to the view.
Is this what you're looking for?

Regular Expression for Link Tags in HTML

I need help with regular expressions. What I'm looking for is a regex that looks for link-tags like this:
<link rel="stylesheet" href="style.css" type="text/css">
Irrespective of where href="" is positioned, I would like to look it up in the link-tag and put a variable named $url in front of style.css with a / following. If it finds http:// or https:// in front of style.css, then i don't want to put the variable in front of it.
I want every link-tag to be replaced.
You can use preg_replace like this to archive desired result:
preg_replace('/(<link\b.+href=")(?!http)([^"]*)(".*>)/', '$1'.$url.'$2$3$4', $html);
So this code (assuming is stored in $html and $url = 'http://mydomain.com/'):
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="style2.css" type="text/css">
<link rel="stylesheet" href="http://google.com/style3.css" type="text/css">
<link rel="stylesheet" href="style4.css" type="text/css">
<link rel="stylesheet" href="https://google.com/style5.css" type="text/css">
<link rel="stylesheet" href="some/path/to/style6.css" type="text/css">
Will be converted to this:
<link rel="stylesheet" href="http://mydomain.com/style.css" type="text/css">
<link rel="stylesheet" href="http://mydomain.com/style2.css" type="text/css">
<link rel="stylesheet" href="http://google.com/style3.css" type="text/css">
<link rel="stylesheet" href="http://mydomain.com/style4.css" type="text/css">
<link rel="stylesheet" href="https://google.com/style5.css" type="text/css">
<link rel="stylesheet" href="http://mydomain.com/some/path/to/style6.css" type="text/css">
The solution to this will never be pretty (or reliable) using a regex, I would recommend using a DOM parser instead, and adding in the attribute with one of its manipulation methods. Have a look at simplehtmldom:
http://simplehtmldom.sourceforge.net/
For example, take a look at this:
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$html->find('div', 1)->class = 'bar';
$html->find('div[id=hello]', 0)->innertext = 'foo';
echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
Try this regular expression:
/(<link.*href=["'])(style.css)(["'].[^>]*>)/gi
Replace portion would look like
\1http://\2\3
or
$1http://$2$3
Note: You may need to escape one of the quotes based on how you quote the string.
I adapted #Juicy Scripter's answer.
It is an improvement for the following.
a) it also works for single quotes as well as double quotes. meaning
/**
*
* Take in html content as string and find all the <script src="yada.js" ... >
* and add $prepend to the src values except when there is http: or https:
*
* #param $html String The html content
* #param $prepend String The prepend we expect in front of all the href in css tags
* #return String The new $html content after find and replace.
*
*/
protected static function _prependAttrForTags($html, $prepend, $tag) {
if ($tag == 'css') {
$element = 'link';
$attr = 'href';
}
else if ($tag == 'js') {
$element = 'script';
$attr = 'src';
}
else if ($tag == 'img') {
$element = 'img';
$attr = 'src';
}
else {
// wrong tag so return unchanged
return $html;
}
// this checks for all the "yada.*"
$html = preg_replace('/(<'.$element.'\b.+'.$attr.'=")(?!http)([^"]*)(".*>)/', '$1'.$prepend.'$2$3$4', $html);
// this checks for all the 'yada.*'
$html = preg_replace('/(<'.$element.'\b.+'.$attr.'='."'".')(?!http)([^"]*)('."'".'.*>)/', '$1'.$prepend.'$2$3$4', $html);
return $html;
}
I'm guessing you're editing a single file - your text editor or IDE should be able to do a regex search/replace for you.
Try this:
Search: href="([^http].*?)"
Replace: href="<?php echo $url; ?>/\1"
If you need to use this in PHP, use preg_replace. Just remember that your search string needs a forward slash before and after it.

Categories