I have a string which I retrieve from a database, I want to calculate the length of the string without spaces but it is displaying a larger value of length(21 characters greater than the actual count) I have removed tab and newline characters and also the php and html tags but no result! I have tried almost every function on the w3schools php reference but I'm unable to find any success. I also have observed that if I don't retrieve the value from the database and input it like this:
$string = "my string";
I get the correct length, please help me. Here is the code:
if($res_tutor[0]['tutor_experience']){
$str = trim(strip_tags($res_tutor[0]['tutor_experience']));
$str = $this->real_string($str);
$space = substr_count($str, ' ');
$experience = strlen($str) - $space;
function real_string($str)
{
$search = array("\t","\n","\r\n","\0","\v");
$replace = array('','','','','');
$str = str_replace($search,$replace,$str);
return $str;
}
And this is the string from the database but as you can see above I have removed all php and html tags using strip_tags() :
<span class=\"experience_font\">You are encouraged to write a short description of yourself, teaching experience and teaching method. You may use the guidelines below to assist you in your writing.<br />
<br />
.Years of teaching experience<br />
.Total number of students taught<br />
.Levels & subjects that you have taught<br />
.The improvements that your students have made<br />
.Other achievements/experience (Relief teaching, a tutor in a tuition centre, Dean's list, scholarship, public speaking etc.)<br />
.For Music (Gigs at Esplanade, Your performances in various locations etc.)</span><br />
</p>
and when I print it, it displays as:
<span class=\"experience_font\">You are encouraged to write a short description of yourself, teaching experience and teaching method. You may use the guidelines below to assist you in your writing.<br />
<br />
.Years of teaching experience<br />
.Total number of students taught<br />
.Levels & subjects that you have taught<br />
.The improvements that your students have made<br />
.Other achievements/experience (Relief teaching, a tutor in a tuition centre, Dean's list, scholarship, public speaking etc.)<br />
.For Music (Gigs at Esplanade, Your performances in various locations etc.)</span><br />
</p>
#Svetilo, not to be rude just wanted to post my findings, your str_replace worked wonderfully, except for the fact that I was still outputting incorrect values with it in the order that you currently have, I found that the following worked flawlessly.
$string = str_replace(array("\t","\r\n","\n","\0","\v"," "),'', $string);
mb_strlen($string, "UTF-8");
Changing around the \r\n & \n made the str_replace not strip out the \n from the \r\n leaving it just a \r.
Cheers.
Try using mb_strlen. http://php.net/manual/en/function.mb-strlen.php
Its more more precise.
mb_strlen($str,"UTF-8")
Where UTF-8 is your default encoding...
To remove all freespaces try something like that..
$string = str_replace(array("\t","\n","\r\n","\0","\v"," "),"",$string);
mb_strlen($string, "UTF-8");
Related
I have the following code:
$message = "Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\n
The seller, $bid_user is making this offer.\n
\nItem Title : $title\n
\nAll the best,\n
$bid_user\n
$email\n
";
echo $message;
$htmlContent = $baseClass->email_friend($item_number, $title, $bid_price, $bid_user, $mcat, $message, $email, $VIEWSTATE, $EVENTVALIDATION, $URL);
The problem is that the new line break (\n) is not working.
Try \r\n in place of \n
The difference between \n and \r\n
It should be noted that this is applicable to line returns in emails. For other scenarios, please refer to rokjarc's answer.
I know this is an old question but anyway it might help someone.
I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).
echo "line 1".PHP_EOL."line 2".PHP_EOL;
If you're planning to show the result in a browser then you have to use "<br>".
EDIT: since your exact question is about emails, things are a bit different.
For pure text emails see Brendan Bullen's accepted answer. For HTML emails
you simply use HTML formatting.
Are you building this string using single or double quotes? \r and \n only work with double quotes, as well as embedded variables. For example:
$foo = 'bar';
echo 'Hello \n $foo!';
will output:
Hello \n $foo!
But:
$foo = 'bar';
echo "Hello \n $foo!";
will output:
Hello
bar!
you can use "Line1<br>Line2"
If you output to html or an html e-mail you will need to use <br> or <br /> instead of \n.
If it's just a text e-mail: Are you perhaps using ' instead of "? Although then your values would not be inserted either...
EDIT: Maybe your class for sending emails has an option for HTML emails and then you can use <br />
1) Double-quotes
$output = "Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n";
If you use double-quotes then \n will work (there will be no newline in browser but see the source code in your browser - the \n characters will be replaced for newlines)
2) Single quotes doesn't have the effect as the double-quotes above:
$output = 'Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n';
all characters will be printed as is (even variables!)
3) Line breaks in HTML
$html_output = "Good news! The item# $item_number on which you placed a bid of <br />$ $bid_price is now available for purchase at your bid price.<br />The seller, $bid_user is making this offer.<br /><br />Item Title : $title<br /><br />All the best,<br /> $bid_user<br />$email<br />";
There will be line breaks in your browser and variables will be replaced with their content.
if you are outputting the code as html - change /n -->
and do echo $message;
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is . so easy way to do this job is replacing all the "\n" with "". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
copyed this ans from this website :
Hello I'm using Curl to get information from Wikipedia,and I want to receive only information about the principal image,I don't want to receive all images of an article..
For example..
If I want to get info about all images of the English Language (http://en.wikipedia.org/wiki/English_language) I should go to this URL:
http://en.wikipedia.org/w/api.php?action=query&titles=English_Language&prop=images
but I receive flags of countries where people speak English in XML:
<?xml version="1.0"?> <api> <query>
<normalized>
<n from="English_language" to="English language" />
</normalized>
<pages>
<page pageid="8569916" ns="0" title="English language">
<images>
<im ns="6" title="File:Anglospeak(800px)Countries.png" />
<im ns="6" title="File:Anglospeak.svg" />
<im ns="6" title="File:Circle frame.svg" />
<im ns="6" title="File:Commons-logo.svg" />
<im ns="6" title="File:Flag of Argentina.svg" />
<im ns="6" title="File:Flag of Aruba.svg" />
<im ns="6" title="File:Flag of Australia.svg" />
<im ns="6" title="File:Flag of Bolivia.svg" />
<im ns="6" title="File:Flag of Brazil.svg" />
<im ns="6" title="File:Flag of Canada.svg" />
I only want the information about the principal image.
There's news! (from 2014)
A new extension, PageImages, is available and also got already installed on the Wikimedia wikis.
Instead of prop=images, use prop=pageimages, and you'll get a pageimage attribute and a <thumbnail> child node for each <page> element.
Admittedly, it's not guaranteed to give the best results, but in your example (English Language) it works well and only yields the map of the geographic distribution, not all the flags.
Also, the OpenSearch API does return an <image> in it's xml representation, but this API is not usable with lists and cannot be combine with the Query API.
This is how I got it working...
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&format=json&callback=?", {
titles: "India",
prop: "pageimages",
pithumbsize: 150
},
function(data) {
var source = "";
var imageUrl = GetAttributeValue(data.query.pages);
if (imageUrl == "") {
$("#wiki").append("<div>No image found</div>");
} else {
var img = "<img src=\"" + imageUrl + "\">"
$("#wiki").append(img);
}
}
);
function GetAttributeValue(data) {
var urli = "";
for (var key in data) {
if (data[key].thumbnail != undefined) {
if (data[key].thumbnail.source != undefined) {
urli = data[key].thumbnail.source;
break;
}
}
}
return urli;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head></head>
<body>
<div id="wiki"></div>
</body>
</html>
As others have noted, Wikipedia articles don't really have any such thing as a "principal image", so your first problem will be deciding how to choose between the different images used on a given page. Some possible selection criteria might be:
Biggest image in the article.
First image exceeding some specific minimum dimensions, e.g. 60 × 60 pixels.
First image referenced directly in the article's source text, rather than through a template.
For the first two options, you'll want to fetch the rendered HTML code of the page via action=parse and use an HTML parser to find the img tags in the code, like this:
http://en.wikipedia.org/w/api.php?action=parse&page=English_language&prop=text|images
(The reason you can't just get the sizes of the images, as used on the page, directly from the API is that that information isn't actually stored anywhere in the MediaWiki database.)
For the last option, what you want is the source wikitext of the article, available via prop=revisions with rvprop=content:
http://en.wikipedia.org/w/api.php?action=query&titles=English_language&prop=revisions|images&rvprop=content
Note that many images in infoboxes and such are specified as parameters to a template, so just parsing for [[Image:...]] syntax will miss some of them. A better solution is probably to just get the list of all images used on the page via prop=images (which you can do in the same query, as I showed above) and look for their names (with or without Image: / File: prefix) in the wikitext.
Keep in mind the various ways in which MediaWiki automatically normalizes page (and image) names: most notably, underscores are mapped to spaces, consecutive whitespace is collapsed to a single space and the first letter of the name is capitalized. If you decide to go this way, here's some sample PHP code that will convert a list of file names into a regexp that should match any of them in wikitext:
foreach ($names as &$name) {
$name = trim( preg_replace( '/[_\s]+/u', ' ', $name ) );
$name = preg_quote( $name, '/' );
$name = preg_replace( '/^(\\\\?.)/us', '(?i:$1)', $name );
$name = preg_replace( '/\\\\? /u', '[_\s]+', $name );
}
$regexp = '/' . implode( '|', $names ) . '/u';
For example, when given the list:
Anglospeak(800px)Countries.png
Anglospeak.svg
Circle frame.svg
Commons-logo.svg
Flag of Argentina.svg
Flag of Aruba.svg
the generated regexp will be:
/(?i:A)nglospeak\(800px\)Countries\.png|(?i:A)nglospeak\.svg|(?i:C)ircle[_\s]+frame\.svg|(?i:C)ommons\-logo\.svg|(?i:F)lag[_\s]+of[_\s]+Argentina\.svg|(?i:F)lag[_\s]+of[_\s]+Aruba\.svg/u
Important addendum
Bergi's answer, above, seemed super great, but I was bashing my head out because I couldn't get it to work.
I needed to include pilicense=any in my query, because otherwise any copyrighted imagery was ignored.
Here's the query I ultimately got working:
https://en.wikipedia.org/w/api.php?action=query&pilicense=any&format=jsonfm&prop=pageimages&generator=search&gsrsearch=My+incategory:English-language_films+prefix:My&gsrlimit=3
I know it's been awhile, but this is one of the first pages I landed on when I started my days-long search for how to do this, so I wanted to share this specifically on this page, for others like me who might come here.
You can limit your query to the first image in the article with the imlimit parameter:
http://en.wikipedia.org/w/api.php?action=query&titles=English_Language&redirects&prop=images&imlimit=1
I have some data that is provided to me as $data, an example of some of the data is...
<div class="widget_output">
<div id="test1">
Some Content
</div>
<ul>
<li>
<p>
<div>768hh</div>
<div>2308d</div>
<div>237ds</div>
<div>23ljk</div>
</p>
</li>
<div id="temp3">
Some more content
</div>
<li>
<p>
<div>lkgh322</div>
<div>32khhg</div>
<div>987dhgk</div>
<div>23lkjh</div>
</p>
</li>
</div>
I am attempting to change the non valid HTML DIVs inside the paragraphs so i end up with this instead...
<div class="widget_output">
<div id="test1">
Some Content
</div>
<ul>
<li>
<p>
<span>768hh</span>
<span>2308d</span>
<span>237ds</span>
<span>23ljk</span>
</p>
</li>
<div id="temp3">
Some more content
</div>
<li>
<p>
<span>lkgh322</span>
<span>32khhg</span>
<span>987dhgk</span>
<span>23lkjh</span>
</p>
</li>
</div>
I am trying to do this using str_replace with something like...
$data = str_replace('<div>', '<span>', $data);
$data = str_replace('</div>', '</span', $data);
Is there a way I can combine these two statements and also make it so that they only affect the 'This is a random item' and not the other occurences?
$data = str_replace(array('<div>', '</div>'), array('<span>', '</span>'), $data);
As long as you didn't give any other details and only asked:
Is there a way I can combine these two statements and also make it so that they only affect the 'This is a random item' and not the other occurences?
Here you go:
$data = str_replace('<div>This is a random item</div>', '<span>This is a random item</span>', $data);
You'll need to use a regular expression to do what you are looking to do, or to actually parse the string as XML and modify it that way. The XML parsing is almost surely the "safest," since as long as the string is valid XML, it will work in a predictable way. Regexes can at times fall prey to strings not being in exactly the expected format, but if your input is predictable enough, they can be ok. To do what you want with regular expressions, you'd so something like
$parsed_string = preg_replace("~<div>(?=This is a random item)(.*?)</div>~", "<span>$1</span>, $input_string);
What's happening here is the regex is looking for a <div> tag which is followed by (using a lookahead assertion) This is a random item. It then captures any text between that tag and the next </div> tag. Finally, it replaces the match with <span>, followed by the captured text from inside the div tags, followed by </span>. This will work fine on the example you posted, but will have problems if, for example, the <div> tag has a class attribute. If you are expecting things like that, either a more complex regular expression would be needed, or full XML parsing might be the best way to go.
I'm a little surprised by the other answers, I thought someone would post a good one, but that hasn't happened. str_replace is not powerful enough in this case, and regular expressions are hit-and-miss, you need to write a parser.
You don't have to write a full HTML-parser, you can cheat a bit.
$in = '<div class="widget_output">
(..)
</div>';
$lines = explode("\n", $in);
$in_paragraph = false;
foreach ($lines as $nr => $line) {
if (strstr($line, "<p>")) {
$in_paragraph = true;
} else if (strstr($line, "</p>")) {
$in_paragraph = false;
} else {
if ($in_paragraph) {
$lines[$nr] = str_replace(array('<div>', '</div>'), array('<span>', '</span>'), $line);
}
}
}
echo implode("\n", $lines);
The critical part here is detecting whether you're in a paragraph or not. And only when you're in a paragraph, do the string replacement.
Note: I'm splitting on newlines (\n) which is not perfect, but works in this case. You might want to improve this part.
Someone has asked a similar question, but the accepted answer doesn't meet my requirements.
Input:
<strong>bold <br /><br /> text</strong><br /><br /><br />
link<br /><br />
<pre>some code</pre>
I'm a single br, <br /> leave me alone.
Expected output:
<p><strong>bold <br /> text</strong><br /></p>
<p>link<br /></p>
<pre>some code</pre>
<p>I'm a single br, <br /> leave me alone.</p>
The accepted answer I mentioned above will convert multiple br to p, and at last wrap all the input with another p. But in my case, you can't wrap pre inside a p tag. Can anyone help?
update
the expected output before this edit was a little bit confusing. the whole point is:
convert multiple br to a single one (achieved with preg_replace('/(<br />)+/', '<br />', $str);)
check for inline elements and unwrapped text (there's no parent element in this case, input is from $_POST) and wrap with <p>, leave block level elements alone.
Do not use regex. Why? See: RegEx match open tags except XHTML self-contained tags
Use proper DOM manipulators. See: http://php.net/manual/en/book.dom.php
EDIT:
I'm not really a fan of giving cookbook-recipes, so here's a solution for changing double <br />'s to text wrapped in <p></p>:
script.php:
<?php
function isBlockElement($nodeName) {
$blockElementsArray = array("pre", "div"); // edit to suit your needs
return in_array($nodeName, $blockElementsArray);
}
function hasBlockParent(&$node) {
if (!($node instanceof DOMNode)) {
// return whatever you wish to return on error
// or throw an exception
}
if (is_null($node->parentNode))
return false;
if (isBlockElement($node->parentNode))
return true;
return hasBlockParent($node->parentNode);
}
$myDom = new DOMDocument;
$myDom->loadHTMLFile("in-file");
$myDom->normalizeDocument();
$elems =& $myDom->getElementsByTagName("*");
for ($i = 0; $i < $elems->length; $i++) {
$element =& $elems->item($i);
if (($element->nextSibling->nodeName == "br" && $element->nextSibling->nextSibling->nodeName == "br") && !hasBlockParent($element)) {
$parent =& $element->parentNode;
$parent->removeChild($element->nextSibling->nextSibling);
$parent->removeChild($element->nextSibling);
// check if there are further nodes on the same level
$nSibling;
if (!is_null($element->nextSibling))
$nSibling = $element->nextSibling;
else
$nSibling = NULL;
// delete the old node
$saved = $parent->removeChild($element);
$newNode = $myDom->createElement("p");
$newNode->appendChild($saved);
if ($nSibling == NULL)
$parent->appendChild($newNode);
else
$parent->insertBefore($newNode, $nSibling);
}
}
$myDom->saveHTMLFile("out-file");
?>
This is not really a full solution, but it's a starting point. This is the best I could write during my lunch break, and please bear in mind that the last time I coded in PHP was about 2 years ago (been doing mostly C++ since then). I was not writing it as a full solution but rather to give you a...well, starting point :)
So anyways, the input file:
[dare2be#schroedinger dom-php]$ cat in-file
<strong>bold <br /><br /> text</strong><br /><br /><br />
link<br /><br />
<pre>some code</pre>
I'm a single br, <br /> leave me alone.
And the output file:
[dare2be#schroedinger dom-php]$ cat out-file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body><p><strong>bold <br><br> text</strong></p><br><p>link</p><pre>some code</pre>
I'm a single br, <br> leave me alone.</body></html>
The whole DOCTYPE mumbo jumbo is a side-effect. The code doesn't do the rest of the things you said, like changing <bold><br><br></bold> to <bold><br></bold>. Also, this whole script is a quick draft, but you'll get the idea.
Alright, I'v got myself an answer, and I believe this is gonna work really well.
It's from WordPress...the wpautop function.
I'v tested it with the input (from my question), and the output is -almost- the same as I expected, I just need to modify it a bit to fit my needs.
Thanks dare2be, but I'm not very familiar with DOM manipulator in PHP.
I have the following code:
$message = "Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\n
The seller, $bid_user is making this offer.\n
\nItem Title : $title\n
\nAll the best,\n
$bid_user\n
$email\n
";
echo $message;
$htmlContent = $baseClass->email_friend($item_number, $title, $bid_price, $bid_user, $mcat, $message, $email, $VIEWSTATE, $EVENTVALIDATION, $URL);
The problem is that the new line break (\n) is not working.
Try \r\n in place of \n
The difference between \n and \r\n
It should be noted that this is applicable to line returns in emails. For other scenarios, please refer to rokjarc's answer.
I know this is an old question but anyway it might help someone.
I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).
echo "line 1".PHP_EOL."line 2".PHP_EOL;
If you're planning to show the result in a browser then you have to use "<br>".
EDIT: since your exact question is about emails, things are a bit different.
For pure text emails see Brendan Bullen's accepted answer. For HTML emails
you simply use HTML formatting.
Are you building this string using single or double quotes? \r and \n only work with double quotes, as well as embedded variables. For example:
$foo = 'bar';
echo 'Hello \n $foo!';
will output:
Hello \n $foo!
But:
$foo = 'bar';
echo "Hello \n $foo!";
will output:
Hello
bar!
you can use "Line1<br>Line2"
If you output to html or an html e-mail you will need to use <br> or <br /> instead of \n.
If it's just a text e-mail: Are you perhaps using ' instead of "? Although then your values would not be inserted either...
EDIT: Maybe your class for sending emails has an option for HTML emails and then you can use <br />
1) Double-quotes
$output = "Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n";
If you use double-quotes then \n will work (there will be no newline in browser but see the source code in your browser - the \n characters will be replaced for newlines)
2) Single quotes doesn't have the effect as the double-quotes above:
$output = 'Good news! The item# $item_number on which you placed a bid of \$ $bid_price is now available for purchase at your bid price.\nThe seller, $bid_user is making this offer.\n\nItem Title : $title\n\nAll the best,\n $bid_user\n$email\n';
all characters will be printed as is (even variables!)
3) Line breaks in HTML
$html_output = "Good news! The item# $item_number on which you placed a bid of <br />$ $bid_price is now available for purchase at your bid price.<br />The seller, $bid_user is making this offer.<br /><br />Item Title : $title<br /><br />All the best,<br /> $bid_user<br />$email<br />";
There will be line breaks in your browser and variables will be replaced with their content.
if you are outputting the code as html - change /n -->
and do echo $message;
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is . so easy way to do this job is replacing all the "\n" with "". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
copyed this ans from this website :