PHP json_encode html element contains unwanted white space - php

I have a problem here.
index.php
ob_start();
include '../view/user.php';
$include = ob_get_clean();
echo json_encode(array(
"success" => true,
"status" => "ok",
"data" => $include));
user.php
<div>
<h2 class='workspace-name'>
<?php echo $name; ?>
</h2>
</div>
The problem is if I indent the HTML element in user.php properly (for readability), there will be a lot of \r\n\t\t\t, provided I use jquery.get to get JSON dataType.
How do I get rid of the /r/t/n? Although it doesn't display on screen I don't feel right about it. Is there any better solution?
Any question please drop in the comment I will edit this. thanks

Why not use str_replace() to replace those characters.
"data" => str_replace(array("\n","\r","\t"),'',$include)));
EDIT: Or use the following when dealing with HTML like <a\thref='#'>Click\n\nHere</a> (thanks to #Salman A for pointing this out)
"data" => str_replace(array("\n","\r","\t"),' ',$include)));

This is so ugly, but it is how I do it:
$html = str_replace("\t",' ',$html);
$html = str_replace("\r\n",'<br />',$html);
I'll be following this for a better answer. There must be a regex way.

$include = preg_replace("#[\\r|\\n|\\t]+#", "", ob_get_clean());

Related

How to find and convert strings that are using curly brackets {site_name} for example in a HTML textarea output?

I am designing a Mail Template editor in my application. I need an idea to find the occurance of specific variables to be able to convert them using preg_replace or preg_match in my code.
For example, my template looks like this: (Sample only) this is what is returned from the textarea variable.
<p>Thank you for your order at {site_name}.</p>
In this example, I would like to replace the {site_url} with a specific variable or code from PHP since I can't parse PHP directly into the textarea.
Hope my question was clear, any help appreciated.
Edit: Is my question clear? I need to replace the {} strings using my own php code. The php code cann't be used in textarea directly. That is why i need to find a templating system that replace predefined variables {... } but convert them using php when interpreting the template.
Do you mean something like this?
<p>Thank you for your order at <?=$site_name?>.</p>
or
<p>Thank you for your order at <?php echo $site_name?>.</p>
edited:
Ahhh, do you mean something like this then:
$html = '<p>Thank you for your order at {site_name}.</p>';
$php_variables_array = array(
"site_url" => "http://www.google.co.uk",
"site_name" => "Google",
);
foreach ($php_variables_array as $key => $value)
{
$html = str_replace("{" . $key . "}", $value, $html);
}
echo $html;
<?php echo $site_name;?>

Extract var value from preg_replace function

I'm trying to simulate a bbcode tag, like code below:
[code]this is code to render[/code]
[code attributeA=arg]this is code to render[/code]
[code attribute C=arg anotherAtributte=anotherArg]this is code to render[/code]
As you can see, the code tag can take as many attributes as needed, also could exists too many code tags in the same "publishment". I only have dealed with easiest tags like img, b, a, i. For example:
$result = preg_replace('#\[link\=(.+)\](.+)\[\/link\]#iUs', '$2', $publishment);
That works fine since it returns the final markup. But, in the code tag I need to have the "attributes" and "values" in array in order to build the markup myselft according to these attributes in order to simulate someting like this:
$code_tag = someFunction("[code ??=?? ...] content [/code]", $array );
//build the markup myself
$attribute1 = array_contains("attribute1", $array)? $array["attribute1"] : "";
echo '<pre {$attribute1}>' . $array['content'] . </pre>
So, I don't expect that you do it entirely for me, I need you just help to take me to the right direction because I never have used regex.
Thank you in advance
I like to use preg_replace_callback for such things:
function codecb($matches)
{
$original=$matches[0];
$parameters=$matches[1];
$content=$matches[2];
return "<pre>". $content ."</pre>";
}
preg_replace_callback("#\[code(.*)\](.+)\[\/code\]#iUs", "codecb", $str);
so when you have [code argA=test argB=test]This is content[/code] then in the function "codecb" you will have:
$original = "[code argA=test argB=test]This is content[/code]"
$parameters = " argA=test argB=test"
$content = "This is content"
and can preg_match the arguments and return the replacement for the whole.

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

The question is the tag <pre> </pre>
I've seen one script I am working on, uses it:
echo ("<pre>");
....
....
echo ("</pre>");
What exactly does it do ?
Is it an Html tag or a PHP ?
I've searched on Google but nothing much comes out of it. When do we usually use that HTML tag?...or PHP tag?
The <prev> tag doesn't exist, but it's probably the <pre> HTML tag to put around debug output, to improve readability. It's not a secret PHP hack. :)
I think you're talking about <pre></pre>. element is displayed in a fixed-width font, and it preserves both spaces and line breaks.
try printing an array with a **<pre>** and whitout **<pre>**
$arr = array(1, 2, 3);
echo '<pre>';
print_r($arr);
echo '</pre>';
print_r($arr);
echo (""); is a php code, and <prev> tries to be HTML, but isn't.
As #pekka said, its probably supposed to be <pre>
It is nor php nor html it sounds like specific xml tag.
The PHP function echo() prints out its input to the web server response.
echo("Hello World!");
prints out Hello World! to the web server response.
echo("<prev>");
prints out the tag to the web server response.
echo do not require valid HTML tags. You can use PHP to print XML, images, excel, HTML and so on.
<prev> is not a HTML tag. Is is a valid XML tag, but since I don't know what page you are working in, i cannot tell you what it is. Maybe it is the root tag of a XML page, or a miswritten <pre> tag.
try this:
$names = array('Jesse', 'joey', 'jelnny', 'justine');
$names = new ArrayObject($names);
echo '<pre>';
print_r($names);
vs this:
$names = array('Jesse', 'joey', 'jelnny', 'justine');
$names = new ArrayObject($names);
//echo '<pre>';
print_r($names);
and it shows what the PRE does very neatly
The <prev>-tag might be an XML-tag.
if you put text within an HTML tag, all spaces and line breaks will be preserved.
Otherwise, the default behaviour is to remove multiple spaces and keep only one space, and ignore line breaks (unless you use the tag).
I'd like to say it's from the time before CSS - not necessarily used to make text more legible, only more formatted.
"<pre>" is an HTML tag. If you insert this line of code in your program
echo "<pre>";
then you will enable the viewing of multiple spaces and line endings. Without this, all \n, \r and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br> you would be able to break the line and go to the next one.
For example,
the code below would be displayed on multiple lines, due to \n line ending specifier.
<?php
echo "<pre>";
printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
printf("Goodbye");
?>
However the following code, would be displayed in one line only (line endings are disregarded).
<?php
printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
printf("Goodbye");
?>
The <pre> is used to define pre-formatted text.
The text within <pre> tag is displayed in a fixed-width font and it preserves both spaces and line breaks that are present in the text.Here I'm printing a JSON FILE without <pre> tag and then with <pre> tag.
Without <pre> tag
https://i.stack.imgur.com/ofRn8.jpg
With <pre> tag
https://i.stack.imgur.com/XzDVg.jpg
$testArray = [
[
"name" => "Dinesh Madusanka",
"gender" => "male"
],
[
"name" => "Tharaka Devinda",
"gender" => "male"
],
[
"name" => "Dumidu Ranasinghearachchi",
"gender" => "male"
]
];
print_r($testArray);
echo "<pre>";
print_r($testArray);
here whatever we write in between the pre tags
it will be interpreted same as html pre tag
ex:
<?php
echo '<pre>';
echo '
code here
will be displayed
as it
is
namaste
';
echo "this line get printed in new line";
echo "</pre>";
echo "Now pre ended:";
echo "this line gets joined to above line";
?>
and content b/w 's font also changes.

Simple PHP Screen Scraping Function

I'm experimenting with autoblogging (i.e., RSS-driven blog posting) using WordPress, and all that's missing is a component to automattically fill in the content of the post with the content that the RSS's URL links to (RSS is irrelevant to the solution).
Using standard PHP 5, how could I create a function called fetchHTML([URL]) that returns the HTML content of a webpage that's found between the <body>...</body> tags?
Please let me know if there are any prerequisite "includes".
Thanks.
Okay, here's a DOM parser code example as requested.
<?php
function fetchHTML( $url )
{
$content = file_get_contents($url);
$html=new DomDocument();
$body=$html->getelementsbytagname('body');
foreach($body as $b){ $content=$b->textContent; break; }//hmm, is there a better way to do that?
return $content;
}
Assuming that it will always be <body> and not <BODY> or <body style="width:100%"> or anything except <body> and </body>, and with the caveat that you shouldn't use regex to parse HTML, even though I'm about to, here ya go:
<?php
function fetchHTML( $url )
{
$feed = '<body>Lots of stuff in here</body>';
$content = file_get_contents( $url );
preg_match( '/<body>([\s\S]{1,})<\/body>/m', $content, $match );
$content = $match[1];
return $content;
} // fetchHTML
?>
If you echo fetchHTML([some url]);, you'll get the html between the body tags.
Please note original caveats.
I think you're better of using a class like SimpleDom -> http://sourceforge.net/projects/simplehtmldom/ to extract the data as you don't need to write such complicated regular expressions

Syntax regex to extract the source of an image

Ahoy there!
I can't "guess" witch syntax should I use to be able to extract the source of an image but simply the web address not the src= neither the quotes?
Here is my piece of code:
function get_all_images_src() {
$content = get_the_content();
preg_match_all('|src="(.*?)"|i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $path) {
echo $path[0];
}
}
When I use it I got this printed:
src="http://project.bechade.fr/wp-content/uploads/2009/09/mer-300x225.jpg"
And I wish to get only this:
http://project.bechade.fr/wp-content/uploads/2009/09/mer-300x225.jpg
Any idea?
Thanks for your help.
Not exactly an answer to your question, but when parsing html, consider using a proper html parser:
foreach($html->find('img') as $element) {
echo $element->src . '<br />';
}
See: http://simplehtmldom.sourceforge.net/
$path[1] instead of $path[0]
echo $path[1];
$path[0] is the full string matched. $path[1] is the first grouping.
You could explode the string using " as a delimeter and then the second item in the array you get would be the right string:
$array = explode('"',$full_src);
$bit_you_want = $array[1];
Reworking your original function, it would be:
function get_all_images_src() {
$content = get_the_content();
preg_match_all('|src="(.*?)"|i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $path) {
$src = explode('"', $path);
echo $src[1];
}
}
Thanks Ithcy for his right answer.
I guess I've been too long to respond because he deleted it, I just don't know where his answer's gone...
So here is the one I've received by mail:
'|src="(.*?)"|i' makes no sense as a
regex. try '|src="([^"]+)"|i' instead.
(Which still isn't the most robust
solution but is better than what
you've got.)
Also, what everyone else said. You
want $path1, NOT $path[0]. You're
already extracting all the src
attributes into $matches[]. That has
nothing to do with $path[0]. If you're
not getting all of the src attributes
in the text, there is a problem
somewhere else in your code.
One more thing - you should use a real
HTML parser for this, because img tags
are not the only tags with src
attributes. If you're using this code
on raw HTML source, it's going to
match not just but
tags, etc.
— ithcy
I did everything he told me to do including using a HTML parser from Bart (2nd answer).
It works like a charm ! Thank you mate...

Categories