Regex/PHP: How to remove linebreaks from within a special pattern - php

i got another problem removing linebreaks from within a token in a template file - the template i have to parse could look something like this:
<html>
<style>
body { color: black }
div {
background-color:#fff;
}
<!-- i need to remove the line breaks within {_WP_token[*]} for parsing //-->
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid
green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
<script>
function() {
console.log('my foo is my castle');
}
</script>
I tried myself without making the break-through. i just succeeded in creating a greedy one, which eats up the first half of the token - here it is:
preg_replace("/(\{_(.*?)(.*\s))/ix", "[LB REMOVED]", $htmlTemplate);
returns
<html>
<style>
body { color: black }
div {
background-color:#fff;
}
<!-- it just ate up the first half of my token ! //-->
<h4>[LB_REMOVED]green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
<script>
function() {
console.log('my foo is my castle');
}
</script>
i made a fiddle here: http://www.phpliveregex.com/p/2EZ
thank you very much in advance.
best regards,
Lupo

Try:
$newString = preg_replace("/[\n\r]/","[LB_REMOVED]", $originalString);

I am not sure I understand you correctly. If you want to change
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid
green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
into
<h4>{_WP_token[id="42";class="foo"; style="border:4px solid green;padding:20px"; onclick="(this.value=confirm('foo'));"]}</h4>
Then you can use this
\{_(.*)[\r\n]+
and replace with $1, See it on Regexr
preg_replace("/\{_(.*)[\r\n]+/", "$1", $htmlTemplate);
I removed all your modifiers, since you do not use them. See Modifiers doc

Related

PHP How to Echo Across the Whole Page

I have created a skin switcher and it is working great, but the code is messy.
I save a cookie and then for some defined css classes, I append '-userDelectedColourFromTheCookie' to the end of the css class to apply it on the page.
So far, I am adding a short php line to the end of every instance of these classes in the html code and as I have said, it is working.
I would prefer to run the php code just once across the whole page and update all occurrences of an array containing the required classes to append the class as above.
I have this at the top of my page:
<?php
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], array("Blue","Red","Grey","Ochre","Mauve"))) echo $classList."-".strtolower($_COOKIE["Theme"]);
?>
<!DOCTYPE html>
... etc
I am defining an array of css classes, then reading the user colour from the cookie and appending it to the css class.
As and example, the default class might be 'theme-3' but of the user selects the blue skin, then this class becomes 'theme-3-blue' and so on.
But it's not working.
Any help would be appreciated.
Don't mess with the element class lists. Use CSS files to apply the colours you want.
Start with a basic CSS design file:
p {
margin-left:10px
font-size: 12pt;
}
h1 {
font-size: 24pt;
}
div {
margin: 10px;
padding 20px;
}
Then create CSS colour files with different colour selections:
blue.css
p {
color:blue;
}
h1 {
color: darkblue;
background-color: lightblue;
}
red.css
p {
color:red;
}
h1 {
color: maroon;
background-color: pink;
}
default.css
p {
color:black;
}
h1 {
color:white;
background-color:black;
}
Then load the colour theme you want
<?php
if (isset($_COOKIE['theme'] && in_array($_COOKIE['theme'], ['red','blue'])) {
$themeCSS = '<link rel="stylesheet" href="'.$_COOKIE['theme'].'.css">';
} else {
$themeCSS = '<link rel="stylesheet" href="default.css">';
}
Then echo $themeCSS in your <head> just like any other <head> element
** I've used standard HTML elements here to illustrate, but any CSS selectors should work.
I believe you want to change the class names inside the $classList variable by appending the selected color theme from the cookies.
You may use the array_map function to modify all elements of your $classList array.
$classList = array("theme-1","theme-2","theme-3","theme-4","theme-5","theme-6","theme-7","theme-8","theme-9","theme-10","theme-hover","theme-heading","theme-drop-content","theme-container","theme-banner-text");
$themeColor = $_COOKIE["Theme"]; // blue
$classList = array_map(function($val) use ($themeColor) { return $val.'-'.$themeColor; }, $classList);
Once you use the array_map function, all elements of the $classList array will be appended with the "-blue".
You can execute and see the output here
http://sandbox.onlinephpfunctions.com/code/6051282e00be1eb7bb7e6a086de20bbcfe9bcc9f
Several good ways to do it. It's a little more complicated with the array of classes but you should be able to adjust this if you need it (not sure why the syntax highlighting is wonky).
Use output buffering and replace at the end:
<?php
ob_start();
?>
<html>
<head></head>
<body>
<div class="theme-1"></div>
</body>
</html>
<?php
$themes = array("Blue","Red","Grey","Ochre","Mauve");
if ((isset($_COOKIE["Theme"])) && in_array($_COOKIE["Theme"], $themes)) {
echo preg_replace('/class="(theme-[^"]+)"/', 'class="$1-' . $_COOKIE['Theme'] . '"', ob_get_clean());
}
With the array of classes, just do it the same way with output buffering but replace like so:
$replace = array_map(function($v) { return "{$v}-{$_COOKIE['Theme']}"; }, $classList);
echo str_replace($classList, $replace, ob_get_clean());

PHP truncate preg_replace URL

Need some suggestions for the methodology to achieve the following:
My current script gets text and if it has URL(s) then it replaces them. The issue is I want to truncate the URLS(s) so they do not break the width of a table or unsightly line break to fit them.
$text = file_get_contents("temp.txt");
$link = preg_replace('#(https?://([-\w\.]+)+(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?)#', '$1', $text);
echo $link;
I am concerned that if I substr() the $link then it won't work if multiple URLs are found. Can you PHP the $1 in the replacement? Any alternatives?
Use preg_replace_callback to modify the match and replacement. This returns the first 10 characters as an example:
$link = preg_replace_callback('#(https?://([-\w\.]+)+(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)?)#',
function($m) {
return ''.substr($m[1], 0, 10).'';
},
$text);
This kind of problem can also be solved on client side using css (I assume you are speaking about the html element table in your question).
To do that, you have to give your cell a fixed size and to set the display property to inline-block. Then you can define the behaviour of the cell when a word is too long using the white-space, overflow and text-overflow properties.
Example:
<html>
<head>
<style>
.mytable td:nth-child(2) {
display: inline-block;
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
</head>
<body>
<table class="mytable">
<tr><td>abcd</td><td>www.smallurl.jp</td><td>efgh</td></tr>
<tr><td>ijkl</td><td>www.a-giant.url/larger/than/the/cell/width</td><td>mnop</td></tr>
</table>
</body>
</html>

PHP/CSS - detect nl2br breaks

I have an array of various input boxes, that when filled, fills up the database with information. Then, from another file, I take the information and print it out to the screen.
What I want to do is to put a symbol in front of each line, however using something like .style br {}; doesn't seem to work.
Reading the from MySQL, using Wordpress if that matters.
EDIT:
I was asked to post how I want it to look like. I think this is pretty straight-forward, but here it is anyway:
# Entry1
# Entry2
# Entry3
EDIT #2:
I would prefer it to be in CSS, if that's not possible, then PHP. Javascript would be the last solution that I want.
I have tried the following and it didn't work at all:
.myform.lines br {
border-bottom: 1px dashed #000000;
background-color: #ffffff;
display: block;
}
Hi have a look at Can you target <br /> with css?
I tried the following html page:
<html><head><title>Test</title>
</head><body>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('br').replaceWith('<br># ');
});
</script>
hi<br>
there<br>
testing<p>
again<p>
</body></html>
This results in
hi
# there
# testing
again
Here is some more code that also does basically the same thing - it adds a symbol (#) at the start of each line (assuming new lines follow a br).
<html><head><title>test2</title>
<script type="text/javascript">
function replaceLineBreaksWithHorizontalRulesInElement(element)
{
elems = element.getElementsByTagName( 'br' );
for ( var i = 0; i < elems.length; i ++ )
{
br = elems.item( i );
txt = document.createTextNode("# ");
br.parentNode.insertBefore(txt, br.nextSibling);
}
}
</script>
</head>
<body onload="replaceLineBreaksWithHorizontalRulesInElement(document)">
testing<br>
one<br>
two<br>
three<br>
four<br>
five<p>
six<p>
</body></html>
Note that this does work in both firefox and internet explorer giving the same results. If you remove the space however then firefox shows a space anyway, and internet explorer shows no space. I think this won't be an issue for you though, since you want the space.
How about
.mySelector:before { content: '#'; }

extract css classes and ID's from source with php

I thought this was going to be pretty simple, but I've been struggling with it now for a while. I know there are CSS parser classes out there that can acheive what I want to do... but I don't need 95% of the functionality they have, so they're not really feasible and would just be too heavy.
All I need to be able to do is pull out any class and/or ID names used in a CSS file via regex. Here's the regex I thought would work, but hasn't.
[^a-z0-9][\w]*(?=\s)
When run against my sample:
.stuffclass {
color:#fff;
background:url('blah.jpg');
}
.newclass{
color:#fff;
background:url('blah.jpg');
}
.oldclass {
color:#fff;
background:url('blah.jpg');
}
#blah.newclass {
color:#fff;
background:url('blah.jpg');
}
.oldclass#blah{
color:#fff;
background:url('blah.jpg');
}
.oldclass #blah {
color:#fff;
background:url('blah.jpg');
}
.oldclass .newclass {
text-shadow:1px 1px 0 #fff;
color:#fff;
background:url('blah.jpg');
}
.oldclass:hover{
color:#fff;
background:url('blah.jpg');
}
.newclass:active {
text-shadow:1px 1px 0 #000;
}
It does match most of what I want, but it's also including the curly brackets and doesn't match the ID's. I need to match the ID's and Classes separately when conjoined. So basically #blah.newclass would be 2 separate matches: #blah AND .newclass.
Any ideas?
===================
FINAL SOLUTION
I wound up using 2 regex to first strip out everything between { and }, then simply matched the selectors based on the remaining input.
Here's a full working example:
//Grab contents of css file
$file = file_get_contents('css/style.css');
//Strip out everything between { and }
$pattern_one = '/(?<=\{)(.*?)(?=\})/s';
//Match any and all selectors (and pseudos)
$pattern_two = '/[\.|#][\w]([:\w]+?)+/';
//Run the first regex pattern on the input
$stripped = preg_replace($pattern_one, '', $file);
//Variable to hold results
$selectors = array();
//Run the second regex pattern on $stripped input
$matches = preg_match_all($pattern_two, $stripped, $selectors);
//Show the results
print_r(array_unique($selectors[0]));
[^a-z0-9][\w]+(?=\s)
I changed your * to a + match
It works fine in RegEXR - an awesome regex development tool: http://gskinner.com/RegExr/ (See bottom right of window to download the desktop version)
This version is based on nealio82's, but adding pseudo-selectors:
[^a-z0-9][\w:-]+(?=\s)
/(?<!:\s)[#.][\w]*/
some thing like this? excludes the #FFFFFF color stuff...
The solution posted by OP works, though it didn't work for me with CSS classes that had hyphens. As such, I've amended the second pattern to work more effectively:
$pattern_two = '/[\.|#]([A-Za-z0-9_\-])*(\s?)+/';

PHP Echo a large block of text

Im new to PHP and I can't figure out what the rules are for using the echo function. For example, if I need to echo a large block of css/js, do I need to add echo to each line of text or is there a way to echo a large block of code with a single echo?
When I try to echo a big block of code like this one, I get an error:
if (is_single()) {
echo '<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname#example.com');
});
</script>';
}else {
}
Is there a better way to echo large blocks of code without a lot of work (adding echo to each line for example)?
Heredoc syntax can be very useful:
// start the string with 3 <'s and then a word
// it doesn't have to be any particular string or length
// but it's common to make it in all caps.
echo <<< EOT
in here is your string
it has the same variable substitution rules
as a double quoted string.
when you end it, put the indicator word at the
start of the line (no spaces before it)
and put a semicolon after it
EOT;
One option is to get out of the php block and just write HTML.
With your code, after the opening curly brace of your if statement, end the PHP:
if (is_single()) { ?>
Then remove the echo ' and the ';
After all your html and css, before the closing }, write:
<? } else {
If the text you want to write to the page is dynamic, it gets a little trickier, but for now this should work fine.
Check out heredoc. Example:
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<"FOOBAR"
Hello World!
FOOBAR;
The is also nowdoc but no parsing is done inside the block.
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;
Echoing text that contains line breaks is fine, and there's no limit on the amount of text or lines you can echo at once (save for available memory).
The error in your code is caused by the unescaped single quotes which appear in the string.
See this line:
$('input_6').hint('ex: myname#example.com');
You'd need to escape those single quotes in a PHP string whether it's a single line or not.
There is another good way to echo large strings, though, and that's to close the PHP block and open it again later:
if (is_single()) {
?>
<link type="text/css" rel="stylesheet" href="http://jotform.com/css/styles/form.css"/><style type="text/css">
.form-label{
width:150px !important;
}
.form-label-left{
width:150px !important;
}
.form-line{
padding:10px;
}
.form-label-right{
width:150px !important;
}
body, html{
margin:0;
padding:0;
background:false;
}
.form-all{
margin:0px auto;
padding-top:20px;
width:650px !important;
color:Black;
font-family:Verdana;
font-size:12px;
}
</style>
<link href="http://jotform.com/css/calendarview.css" rel="stylesheet" type="text/css" />
<script src="http://jotform.com/js/prototype.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus.js" type="text/javascript"></script>
<script src="http://jotform.com/js/protoplus-ui.js" type="text/javascript"></script>
<script src="http://jotform.com/js/jotform.js?v3" type="text/javascript"></script>
<script src="http://jotform.com/js/location.js" type="text/javascript"></script>
<script src="http://jotform.com/js/calendarview.js" type="text/javascript"></script>
<script type="text/javascript">
JotForm.init(function(){
$('input_6').hint('ex: myname#example.com');
});
</script>
<?php
}else {
}
Or another alternative, which is probably better for readability, is to put all that static HTML into another page and include() it.
Man, PHP is not perl!
PHP can just escape from HTML :)
http://www.php.net/manual/en/language.basic-syntax.phpmode.php
if (is_single()) {
//now we just close PHP tag
?>
</style>
<script>
<blah blah blah>
<?php
//open it back. here is your PHP again. easy!
}
?>
I wonder why such many people stuck to ugly heredoc.
Your problem is actually caused by:
$('input_6').hint('ex: myname#example.com');
You need to escape the single quotes to be \'
However: Using a Heredoc is a much better idea, as it will be much cleaner overall.
To expand on #hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:
<?php if (is_single()): ?>
<p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
<p>This will be shown otherwise.</p>
<?php endif; ?>
Just break out where you need to.
<html>
(html code)
<?php
(php code)
?>
(html code)
</html>
Do not use shortened-form. <? conflicts with XML and is disabled by default on most servers.
I prefer to concatenate multiple Strings together. This works either for echo AND for variables.
Also some IDEs auto-initialize new lines if you hit enter.
This Syntax also generate small output because there are much less whitespaces in the strings.
echo ''
.'one {'
.' color: red;'
.'}'
;
$foo = ''
.'<h1>' . $bar . '</h1>' // insert value of bar
.$bar // insert value of bar again
."<p>$bar</p>" // and again
."<p>You can also use Double-Quoted \t Strings for single lines. \n To use Escape Sequences.</p>"
// also you can insert comments in middle, which aren't in the string.
.'<p>Or to insert Escape Sequences in middle '."\n".' of a string</p>'
;
Normally i start with an empty string and then append bit by bit to it:
$foo = '';
$foo .= 'function sayHello()'
.' alert( "Hello" );'
."}\n";
$foo .= 'function sum( a , b )'
.'{'
.' return a + b ;'
."}\n";
(Please stop Posts like "uh. You answer to an five jears old Question." Why not? There are much people searching for an answer. And what's wrong to use five year old ideas? If they don't find "their" solution they would open a new Question. Then the first five answers are only "use the search function before you ask!" So. I give you another solution to solve problems like this.)
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
You can achieve that by printing your string like:
<?php $string ='here is your string.'; print_r($string); ?>

Categories