Can you combine a PHP function and string in the same echo statement? Currently, I have this code that grabs a photo's caption, then shortens it to 25 characters or less, stopping at the nearest blank space so it can fit the whole word.
echo substr($caption,0,strpos($caption,' ',25));
echo " ...";
Example output: changes "This is way too long to fit in this foobar small area preview box" to "This is way too long to..."
I'd like to be able to combine the 'substr' and '...' into the same echo statement. I tried the following, but it didn't work:
echo "{substr($caption,0,strpos($caption,' ',25))} ...";
Any ideas?
The , is great for this, and much faster than the ., which has the overhead of concatenating the string.
echo substr($caption, 0, strpos($caption, ' ', 25)), '...';
EDIT: To clarify, the , just simply sends all the strings, separated by the comma, to echo, and thus is equal to the separate line echo statments. The DOT operator performs concatenation. You can use as many commas as you want, i.e. echo strFunction1(), ' some text ', strFunction2(), '...';
Try:
echo substr($caption,0,strpos($caption,' ',25)) . '...';
Related
I have a text file with three words in it; each on a separate row: child, toy, people.
I am using the Laravel Str::plural() function to pluralize each word and display the results with line breaks.
It works perfectly when I use the words in my code without a file, as so:
$output1 = Str::plural('child');
$output2 = Str::plural('toy');
$output3 = Str::plural('person');
$string = $output1 . "\r\n" . $output2 . "\r\n" . $output3;
echo nl2br($string);
The result shows as follows:
children
toys
people
However, when I use a "while" loop through a file containing these words, it only pluralizes the last word.
This is the "while" loop code:
$myFile = new \SplFileObject("words.txt");
while (!$myFile->eof()) {
$string = Str::plural($myFile->fgets());
echo nl2br($string);
}
As you can see from the result, only the last word is pluralized:
child
toy
people
Since my loop has brackets {} I assumed that BOTH lines of codes execute for each loop but I guess in PHP it's not like that? Any idea how to fix my "while" loop?
There may be some extra spaces or line-ending characters, so you'll need to trim the string before you pluralize it.
$str = trim($myFile->fgets()); // Remove white space from the word/line
$string = Str::plural($str);
However, the nl2br will not work since there are no longer any new lines, so you'll want to append the br to the words.
echo "$string<br>";
I think you have written words in file on separate rows;
It means that of the end of each row you have hidden symbols \r\n
I can say it because "person" is pluralized correclty and there is no other words after that in your example.
You can easy check it with debug or var_dump function;
echo var_dump($yourString);
You will see something like this
string(5) "toy
"
[PHP]I have a variable for storing strings (a BIIGGG page source code as string), I want to echo only interesting strings (that I need to extract to use in a project, dozens of them), and they are inside the quotation marks of the tag
but I just want to capture the values that start with the letter: N (news)
[<a href="/news7044449/exclusive_news_sunday_"]
<a href="/n[ews7044449/exclusive_news_sunday_]"
that is, I think you will have to work with match using: [a href="/n]
how to do that to define that the echo will delete all the texts of the variable, showing only:
note that there are other hrefs tags with values that start with other letters, such as the letter 'P' : href="/profiles... (This does not interest me.)
$string = '</div><span class="news-hd-mark">HD</span></div><p>exclusive_news_sunday_</p><p class="metadata"><span class="bg">Czech AV<span class="mobile-hide"> - 5.4M Views</span>
- <span class="duration">7 min</span></span></p></div><script>xv.thumbs.preparenews(7044449);</script>
<div id="news_31720715" class="thumb-block "><div class="thumb-inside"><div class="thumb"><a href="/news31720715/my_sister_running_every_single_morning"><img src="https://static-hw.xnewss.com/img/lightbox/lightbox-blank.gif"';
I imagine something like this:
$removes_everything_except_values_from_the_href_tag_starting_with_the_letter_n = ('/something regex expresion I think /' or preg_match, substring?);
echo $string = str_replace($removes_everything_except_values_from_the_href_tag_starting_with_the_letter_n,'',$string);
expected output: /news7044449/exclusive_news_sunday_
NOTE: it is not essential to be through a variable, it can be from a .txt file the place where the extracts will be extracted, and not necessarily a variable.
thanks.
I believe this will help her.
<?php
$source = file_get_contents("code.html");
preg_match_all("/<a href=\"(\/n(?:.+?))\"[^>]*>/", $source, $results);
var_export( end($results) );
Step by Step Regex:
Regex Demo
Regex Debugger
To get just the links out of the $results array from Valdeir's answer:
foreach ($results as $r) {
echo $r;
// alt: to display them with an HTML break tag after each one
echo $r."<br>\n";
}
I would like to replace array string values which contains multiple special characters to normal one.
Tried Code (array values):
$data['ENV_TEST'] = "rambo";
$data['ENV_DEV'] = "Project Bribara<"${ENV_TEST}"#gmail.com>"
echo str_replace("${ENV_TEST}", $data['ENV_DEV'], $data['ENV_DEV']);
also tried
echo str_replace("\"${ENV_TEST}\"", $data['ENV_DEV'], $data['ENV_DEV']);
Expected:
"Project Bribara<rambo#gmail.com>"
Actual:
"Project Bribara<"${ENV_TEST}"#gmail.com>"
How can I get the expected output?
You should on PHP strings sometime. The important part about double quoted strings for your question is that you need to put a backslash before every $ and every " inside your string. Your code will then look like this:
$data['ENV_TEST'] = "rambo";
$data['ENV_DEV'] = "Project Bribara<\"\${ENV_TEST}\"#gmail.com>";
echo str_replace("\${ENV_TEST}", $data['ENV_TEST'], $data['ENV_DEV']);
//also tried
echo "\n\n";
echo str_replace("\"\${ENV_TEST}\"", $data['ENV_TEST'], $data['ENV_DEV']);
If you use single quoted strings you don't need to escape $ (see the manual), and instead of \", you would need to escape single quotes (but there aren't any in your example).
$data['ENV_TEST'] = "rambo";
$data['ENV_DEV'] = 'Project Bribara<"${ENV_TEST}"#gmail.com>';
echo str_replace("\${ENV_TEST}", $data['ENV_TEST'], $data['ENV_DEV']);
//also tried
echo "\n\n";
echo str_replace('"${ENV_TEST}"', $data['ENV_TEST'], $data['ENV_DEV']);
I also fixed a missing semicolon and replaced DEV with TEST in one place.
String concatenation in PHP is done through the . operator. Your code would be:
$data['ENV_DEV'] = "Project Bribara<".$data['ENV_TEST']."#gmail.com>"
I have a variable a such $var:
$var = "One, Two, Three";
I can echo the variable without any problems the output is:
One, Two, Three
Is it possible, when echoing the variable to add a line break where there is a ,, so it would look like this?
One,
Two,
Three
If you echo the text to HTML, you can do the following:
echo str_replace(",", ", <br/>", $var);
If you echo the string to a console or a text file through redirection, just use the PHP_EOL constant, which represents the correct end-of-line string for the current platform ie. "\n" for Unix, "\r\n" for Windows:
echo str_replace(",", "," . PHP_EOL, $var);
You can use this:
$var = "One,\nTwo,\nThree";
\n is the line break, and makes sense if you are working through the terminal
You use \n to force a new line when outputting to a terminal.
$var = "One,\nTwo,\nThree";
You can use the HTML <br /> to output a new line on a web browser.
$var = "One,<br />Two,<br />Three";
You can use the str_replace function once you determine which type you want.
Make use of <br> tag
$var = "One, <br>Two, <br>Three";
(or) Make use of str_replace in PHP
<?php
$var = "One, Two, Three";
echo str_replace(',',',<br>',$var); // code replaces all your commas with , and a <br> tag
Explode the string with the comma as separator, then iterate through the resulting array, adding line breaks (with the br tag if outputting to browser, or newline (\n) escape sequence if outputting to terminal) when needed?
I have this:
<div> 16</div>
and I want this:
<div><span>16</span></div>
Currently, this is the only way I can make it work:
preg_replace("/(\D)(16)(\D)/", "$1<span>$2</span>$3", "<div> 16</div>")
If I leave off the $3, I get:
<div><span>16</span>/div>
Not quite sure what your after, but the following is more generic:
$value = "<div> 16 </div>";
echo(preg_replace('%(<(\D+)[^>]*>)\s*([^\s]*)\s*(</\2>)%', '\1<span>\3</span>\4', $value));
Which would result in:
<div><span>16</span></div>
Even if the value were:
<p> 16 </div>
It would result in:
<p><span>16</span></p>
I think you meant to say you're using the following:
print preg_replace("/(\\D+)(16)(\\D+)/", "$1<span>$2</span>$3", "<div>16</div>");
There's nothing wrong with that. $3 is going to contain everything matched in the second (\D+) group. If you leave it off, obviously it's not going to magically appear.
Note that your code in the question had some errors:
You need to escape your \'s in a string.
You need to use \D+ to match multiple characters.
You have a space before 16 in your string, but you're not taking this into account in your regex. I removed the space, but if you want to allow for it you should use \s* to match any number of whitespace characters.
The order of your parameters was incorrect.
Try following -
$str = "<div class=\"number\"> 16</div>";
$formatted_str = preg_replace("/(<div\b[^>]*>)(.*?)<\/div>/i", "$1<span>$2</span></div>", $s);
echo $formatted_str;
This is what ended up working the best:
preg_replace('/(<.*>)\s*('. $page . ')\s*(<.*>)/i', "$1" . '<span class="curPage">' . "$2" . '</span>' . "$3", $pagination)
What I found was that I didn't know for sure what tags would precede or follow the page number.