I am programming on wordpress and I want to edit a php file. I want the text to be displayed with line breaks and not all in one line.
Here is my code(I want jonh in one line and travolta in another but it gets displayed in one):
<div class="slide">
<img class="animated fade_left" src='<?php echo esc_url(onepage_get_option('onepage_testimonial_2_image', ONEPAGE_DIR_URI . "assets/images/team2.jpg")); ?>' onmouseover="javascript: this.title = '';" title="">
<div class="bx-caption animated fade_right"><span><a class="arrow"></a><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_content', __('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.','one-page'))); ?><a class="testimonial"><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_name', __('john \n travolta','one-page'))); ?></a></span></div>
Any suggestions?
If you want the link / element with the class testimonial on a new line, I would use css as that keeps it flexible and makes it easy to change if you want to do it differently in the future.
So in your css file:
.testimonial {
display: block;
}
In general, I would try to keep presentational stuff out of the php code.
Related
Hey i want to display some html/css depending on how many rows there are in database basically. Is there a way to do this without echo? Because i'm lost when i have to use many ' '. Here is code sample
<?php foreach ($result as $row) {
}?>
<div id="abox">
<div class="abox-top">
Order x
</div>
<div class="abox-panel">
<p>lorem ipsum</p>
</div>
<br>
<div class="abox-top">
lorem</div>
<div class="abox-panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ac convallis diam, vitae rhoncus enim. Proin eu turpis at ligula posuere condimentum nec eu massa. Donec porta tellus ante, non semper risus sagittis at. Pellentesque sollicitudin sodales fringilla. Ut efficitur urna eget arcu luctus lobortis. Proin ut tellus non lacus dapibus vehicula non sit amet ante. Ut nibh justo, posuere sit amet fringilla eget, aliquam mattis urna.</p>
</div>
There's nothing complicated about it:
Simple/ugly:
<?php while($row = fetch()) { ?>
<div>
<?php echo $row['somefield'] ?>
</div>
<? } ?>
Alternative:
<?php
while ($row = fetch()) {
echo <<<EOL
<div>
{$row['somefield']}
</div>
EOL;
}
and then of course there's any number of templating systems, which claim to separate logic from display, and then litter the display with their OWN logic system anyways.
you can simply use <?= short opening tag introduced in php 5.3 before PHP 5.4.0 came out you had to enable short_open_tag ini but after 5.4.0 tag
here is an example
<?php $var='hello, world'; ?>
<?=$var ?> // outputs world
hope it helps.
Templates engines makes your life a pie
Take Smarty for example, it's pretty good template library. What template engine does is fetch variables to pre defined templates.
Your code in simple php:
<?php
echo 'My name is '. $name. ', that's why I'm awesome <br>';
foreach ($data as $value) {
echo $value['name'].' is awesome to!';
}
?>
Code in smarty:
My name is {$name}, that's why I'm awesome <br>
{foreach $data as $value}
{$value} is awesome to!
{/foreach}
Template engines pros:
Templates are held in separate custom named files. (i.e users.tpl, registration.tpl etc)
Smarty Caches your views (templates).
Simple to use i.e {$views + ($viewsToday/$ratio)}.
A lot of helpers.
You can create custom plugins/functions.
Easy to use and debug.
Most importantly: It separates your php code from html!
Template engines cons:
Sometimes hard to grip the concept of working for beginner.
Don't know any more actually
When I dont want to use a template engine (I like Twig, btw), I do something like this:
1) Write a separate file with the html code and some custom tags where data should be presented:
file "row_template.html":
<div class="abox-top">{{ TOP }}</div>
<div class="abox-panel"><p>{{ PANEL }}</p></div>
2) And then, read that file and do the replacements in the loop:
$row_template = file_get_contents('row_template.html');
foreach ($result as $row) {
$replaces = array(
'{{ TOP }}' => $row['top'],
'{{ PANEL }}' => $row['panel']
);
print str_replace(
array_keys($replaces),
array_values($replaces),
$row_template
);
}
In addition, you can change the content of "row_template.html" without touching the php code.
Clean and nice to the eye!
I have problem with regex tag html. Any one please help me!
Thanks this is some case of me... I have search and think but not do it.
Case 1
// My input to regex
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit <br/><img src="img.jpg/> sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua<p>
// Out Put after regex
Lorem ipsum dolor sit amet, consectetur adipisicing elit <br/><img src="img.jpg/> sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua
Case 2
// My input to regex
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
// Out put after regex
Lorem ipsum dolor sit amet, consectetur adipisicing elit
Case 3
// My input to regex
<p><ul>...</ul><p>
//Out put after regex
NULL
I'm guessing something like this is what you're after (example in javascript).
function checkParagraph(str)
{
var result = str.match(/^<p>([^<].*[^>])<\/p>$/i);
if (result) return result[1];
else return null;
}
alert(checkParagraph("<p>Lorem ipsum <br/><img src=\"img.jpg\"/> magna aliqua</p>"));
alert(checkParagraph("<p>Lorem ipsum magna aliqua</p>"));
alert(checkParagraph("<p><img src=\"img.jpg\"/></p>"));
With the additional information about only allowing BR, IMG, A and IMG-inside-A tags, the regex is quite different:
function checkParagraph(str)
{
var result = str.match(/^<p>(([^<>]+|<br\/>|<img[^>]+>|<a[^>]+>[^<>]*<\/a>|<a[^>]+><img[^>]+><\/a>)*)<\/p>$/i);
if (result) return result[1];
else return null;
}
alert(checkParagraph("Lorem ipsum magna aliqua"));
alert(checkParagraph("<p>Lorem ipsum magna aliqua</p>"));
alert(checkParagraph("<p>Lorem ipsum <br/> magna aliqua</p>"));
alert(checkParagraph("<p>Lorem ipsum magna aliqua</p>"));
alert(checkParagraph("<p>Lorem ipsum <img src=\"img.jpg\"/> magna aliqua</p>"));
alert(checkParagraph("<p>Lorem ipsum <br/><img src=\"img.jpg\"/> magna aliqua</p>"));
alert(checkParagraph("<p><br/><img src=\"img.jpg\"/></p>"));
alert(checkParagraph("<p><span>magna</span> aliqua</p>"));
alert(checkParagraph("<p><span>magna</span> aliqua</p>"));
alert(checkParagraph("<p><br/><img src=\"img.jpg\"/><span>magna</span> aliqua</p>"));
Break-down of the regex:
/.../i -> case insensitive for upper and lower case tags
^<p>...<\/p>$ -> input is enclosed in P tag
(...) -> the capture group between the brackets will become result[1]
(...|...)* -> any number of the following options:
[^<>]+ -> option 1: any text without tags
<br\/> -> option 2: a BR tag
<img[^>]+> -> option 3: an IMG tag
<a[^>]+>[^<>]*<\/a> -> option 4: an A tag with text inside
<a[^>]+><img[^>]+><\/a> -> option 5: an A tag with an IMG tag inside
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
PHP script that can extract text between multiple title tags of certain website?
(4 answers)
Closed 9 years ago.
I need the script to come to defined web address, and then exctract from this part of html code which is present multiple times on the web all title values. This is just one example from the site:
<td><a title="Articlesiteslist.com Analysis" href="http://www.statscrop.com/www/articlesiteslist.com"><img src="http://static.statscrop.com/favicons.png" class="data_original img_icon" data-original="http://s2.googleusercontent.com/s2/favicons?domain_url=articlesiteslist.com" width="16" height="16" alt="articlesiteslist.com" title="articlesiteslist.com"> articlesiteslist.com</a></td>
Tomorrow
From this I need only the title, so from title="example" only example value should come out.
Thanks a lot for help, trying to solve this problem for two days now.
To expand the idea of Amal Murali you need to make the following.
For example you want to load some "a.html" file:
<html>
<body>
Lorem ipsum dolor
<a title="Ravellavegas.com Analysis" href="http://somewebsite.com/" />
sit amet, consectetur adipisicing elit, sed do eiusmod tempor
<a title="Articlesiteslist.com Analysis" href="http://someanotherwebsite.com/" />
incididunt ut labore et dolore magna aliqua.
</body>
</html>
Then, you have to write the script as follows:
<?php
$dom = new DOMDocument();
$dom->load('a.html');
foreach ($dom->getElementsByTagName('a') as $tag) {
echo $tag->getAttribute('title').'<br/>';
}
?>
This outputs:
Ravellavegas.com Analysis
Articlesiteslist.com Analysis
Variant #2
<?php
$text = <<<EOT
<html>
<body>
Lorem ipsum dolor
<a title="Ravellavegas.com Analysis" href="http://somewebsite.com/" />
sit amet, consectetur adipisicing elit, sed do eiusmod tempor
<a title="Articlesiteslist.com Analysis" href="http://someanotherwebsite.com/" />
incididunt ut labore et dolore magna aliqua.
</body>
</html>
EOT;
preg_match_all('/title=".*?"/is', $text, $matches);
foreach($matches[0] as $m)
{
$m = str_replace('title="', "", $m);
$m = str_replace('"', '', $m);
echo htmlentities($m)."<br />";
}
?>
This still outputs:
Ravellavegas.com Analysis
Articlesiteslist.com Analysis
I create a simple backed area for my client to post new job openings and was wanting to give them the ability to format the text a little by adding line breaks in the job description text that will be visible on the front end.
The job openings are stored in a MySQL database.
Example of what I'm talking about:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat.
I've would like the breaks to happen when my client hits enter / return on the keyboard.
Any help on this matter would be appreciated.
------------UPDATE------------
okay so after much trial and error I got it somewhat working.
I added this line in my upload / action code.
$description = nl2br(htmlspecialchars($_POST['description']));
Full upload code is:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$date = mysql_real_escape_string($_POST["date"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$description = nl2br(htmlspecialchars($_POST['description']));
// Insert record into database by executing the following query:
$sql="INSERT INTO hire (title, description, date) "."VALUES('$title','$description','$date')";
$retval = mysql_query($sql);
echo "The position was added to employment page.<br />
<a href='employment.php'>Post another position.</a><br />";
?>
Then on my form I added this to the textarea, but I get an error.
FYI that is line 80 the error is refering to.
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />","",$description); ?></textarea>
</div>
Here is what the error looks like.
Here is my results page code:
<?php
$images = mysql_query("SELECT * FROM hire ORDER BY ID DESC LIMIT 10");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>">
<div class="box white-bg">
<h2 class="red3-tx"><?=$image["title"] ?> <span class="date-posted blue2-tx"><?=$image["date"] ?></span></h2>
<div class="dotline"></div>
<article class="blue3-tx"><?=$image["description"] ?><br />
<br />
For more information please call ###-###-####.</article>
</div>
</li>
<?php
}
?>
If I delete all that error copy and write out a real position with line breaks it works.
I have no idea how to fix the error though.
Again any help would be appreciated.
Thanks!
you can use str_replace
$statement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat."
$statement = str_replace(chr(13),"<br/>", $statement);
query example : INSERT INTO table (statement) VALUES ('$statement');
hope this can help you
EDIT :
if you want display the result at textarea from database u can using this code
$des = $row['description'] //my assumption that your feild name at table inside mySQL is description
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?></textarea>
</div>
hope this edit can help your second problem
I would start by answering a couple of questions first
Do I want my database to store html-formatted user input?
Is the data going to be editable afterwards?
Since you seem to want only nl2br, a simple approach would be to save the content as is in the database, then use nl2br() on the output side as Marcin Orlowski suggested.
How could I convert everyting between a tag to html enities:
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore
magna aliquyam erat, sed diam voluptua.
<code class="highlight sql">
CREATE TABLE `comments`
</code>
<h1>Next step</h1>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et
dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum.
<b>Stet clita kasd gubergren, no sea takimata sanctus</b> est Lorem
dolor sit amet. Lorem ipsum dolor sit amet, consetetur
sadipscing elitr, sed diam nonumy eirmod tempor invidunt
ut labore et dolore magna aliquyam erat, sed diam voluptua:
<code class="highlight php">
<?php
$host = "localhost";
?>
</code>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr.
Note: That example above is a string which I could convert in PHP.
This comes down to a regex for me. And before you start shouting it is possible to reliably match & replace subsets of html, as long as there are no nesting tags.
This is the easy way tbh. A regex to match a tag start till end and apply a function to the matches / encoding what we need and replacing it.
Heres the code:
<?php
$string = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et dolore
magna aliquyam erat, sed diam voluptua.
<code class="highlight sql">
CREATE TABLE `comments`&
</code>
<h1>Next step</h1>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
sed diam nonumy eirmod tempor invidunt ut labore et
dolore magna aliquyam erat, sed diam voluptua.
At vero eos et accusam et justo duo dolores et ea rebum.
<b>Stet clita kasd gubergren&, no sea takimata sanctus</b> est Lorem
dolor sit amet. Lorem ipsum dolor sit amet, consetetur
sadipscing elitr, sed diam nonumy " eirmod " tempor invidunt
ut labore et dolore magna aliq&uyam erat, sed diam voluptua:
<code class="highlight php">
<?php
* $host = "localhost";
?>&
</code>
Lorem ipsum dolor sit amet, consetetur sadipscing elitr.';
echo preg_replace("/(<code[^>]*?>)(.*?)(<\/code>)/se", "
stripslashes('$1').
htmlentities(stripslashes('$2')).
stripslashes('$3')
", $string);
And heres a working testcase on codepad
http://codepad.org/MhKwfOQl
This will work as long as there are no nasty nested tags / corrupted html.
I would still advise you to try and make sure you save the data as you want to make it visible, encoded where needed.
If you want to replace between a different set of tags change the regex.
Update: It seemed that $host was being parsed by php... and ofrourse we don't want this. This happened because php evaluates the replacement string as php which then executes the given functions and inputs the found strings into those functions, and if that string is encapsulated by double qoutes it will parse those strings too... heh what a hassle.
And another problem then arises, php escapes single and double qoutes in matches so they won't generate parse errors, this ment that any qoutes in the matches had to be stripped from their slashes too... resulting in the pretty long replace string.
Although a regular expression or parser may give you a solution to this puzzle, I think you may be going about your goal the wrong way.
Taken from the comments below the question:
#Poru How is that string generated?
#Phil: Fetched from database. It's
the content of a tutorial. It's an own development "CMS".
If you are storing this string in a database, and it's function is to return HTML content, you should be storing the content ready to serve as HTML, which means you must escape the appropriate characters with their equivalent HTML entities.
This was the advice already offered to you in this question: https://stackoverflow.com/questions/7059776/include-source-code-in-html-valid/7059834
The characters that must be escaped are explained here (among other various references):
http://php.net/manual/en/function.htmlspecialchars.php
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
"'" (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
If in fact this is the case, and this string is supposed to be HTML output and has no other function, it doesn't make any sense to save it as invalid HTML, or at least not what you intend it to be.
If you must store your code examples unescaped, consider a separate database table for these snippets, and simply run htmlspecialchars() on them before outputting it to the HTML document. You could even assign a language to each record, and use the appropriate syntax highlighting tool for each case automatically.
What you are attempting, in my opinion, is not the appropriate solution to this particular problem, in this context. Escaping the characters and having your HTML content ready to be output to screen in it's current form is the way to go.
$dom = new DOMDocument;
$dom->loadHTML(...);
$tags = $dom->getElementsByTagName('tag');
foreach($tags as $tag) {
$tag->nodeValue = htmlentities($tag->nodeValue);
}
$dom->saveHTML();