Bold the first two words from a sentence - php

In PHP, how can I bold the first two words from a sentence?
Thank you!

Actually, using the "limit" parameter in the function explode (3rd parameter, optional, check the function spec) you can skip the loop and make your code much simpler:
$words_array = explode(" ",$sentence,3);
$new_sencence = ( count($words_array)>2 )?
"<strong>".$words_array[0]." ".$words_array[1]."</strong> ".$words_array[2] :
"<strong>".$sentence."</strong>"; //sentence is 2 words or less, just bold it
EDIT: took care of sentences with 2 words or less

preg_replace('/^(\S+(\s+\S+)?)/', '<b>$1</b>', $sentence)

You need to break things down into steps...
1) You have a sentence, like this:
$Sentence = "Hello everybody in the world.";
2) You need to get the first two words. There are two options. You can either split the sentence on every space, or you can find the position of the second space. We'll use the first option for now...
$Words = explode(" ", $Sentence);
3) We re-assemble it all, inserting a bit of HTML to make things bold...
$WordCount = count($Words);
$NewSentence = '';
for ($i = 0; $i < $WordCount; ++$i) {
if ($i < 2) {
$NewSentence .= '<strong>' . $Words[$i] . '</strong> ';
} else {
$NewSentence .= $Words[$i] . ' ';
}
}
echo $NewSentence;

Related

PHP Replace Leading Zeros with Same Number of Spaces

I'd like to replace a string like 0001 with " 1" with 3 spaces.
I've tried str_replace but that doesn't work on 0010.
I've tried some preg_replace but can't get the replacement right to replace the same number
I've written this basic thing and it works, but am looking for something more efficient if possible.
$pin = '0010';
$temp = ltrim($pin, '0');
$spaces = strlen($pin) - strlen($temp);
for ($x=1;$x<=$spaces;$x++) $temp = ' '.$temp;
echo $temp;
Closest I got with preg_replace was this but I'm not sure what to do with replacement:
preg_replace('/0+/', ' ', $pin)
\G for the win!
https://www.regular-expressions.info/continue.html
\G will match the start of the string and continue to match until it can't.
What is the use of '\G' anchor in regex?
Match a zero from the start of the string, then match every following zero one-at-a-time. Replace every matched zero with a space.
Code: (Demo)
$pin = '0010';
var_export(preg_replace('~\G0~', ' ', $pin));
Output:
' 10'
I don't see how to do this any easier with a regular expression, but you could make your other code more concise by using str_repeat:
$pin = '0010';
$temp = ltrim($pin, '0');
$spaces = strlen($pin) - strlen($temp);
$new_pin = str_repeat(' ', $spaces) . $temp;
echo $new_pin;
You said:
but am looking for something more efficient if possible
First, note that a one-liner isn't necessarily efficient(as you tried for preg_replace() and regex is actually a bit slower since it gets compiled first).
Second, you can better adopt for just a 2 pass approach over the string. This also edits the string in-place without extra string variables which is desirable in your case.
Snippet:
<?php
$str = '000010';
$len = strlen($str);
for($i = 0; $i < $len; ++$i){
if($str[$i] == '0'){
$str[$i] = ' ';
}else{
break;
}
}
echo $str;

php string manipulation issues

I have the following string...
$string = "True is True (5-7 years)";
what I want is to get - TiT(5-7 years)
I have tried the following code but no luck...
$string = "True is True (5-7 years)";
$explodedString = explode(" ",$string);
for($i = 0; $i < 4; $i++){
$tempString = substr($explodedString[$i], 0, 1);
$finalString .= $tempString;
}
In short, I need the first three words of its initials and the remaining in bracket is as it is like this.... TiT(5-7 years). how?
This a good case for using regular expressions:
$str = 'True is True (5-7 years)';
preg_match_all('~\([^()]*\)|\b\w~', $str, $matches);
echo implode("", $matches[0]); // TiT(5-7 years)
Regex breakdown:
\([^()]*\) Match anything inside parentheses including themselves
| Or
\b\w Match first word character from a word
Your loop is going one element too far. If you want the first letter of the first 3 words, it should be $i < 3.
Then you should use array_slice() and implode() to concatenate the rest of the array.
for ($i = 0; $i < 3; $i++) {
$finalString .= $explodedString[$i][0];
}
$finalString .= implode(' ', array_slice($explodedString, 3));
DEMO
$string = "True is True (5-7 years)";
$new_string = preg_replace('/^([a-z])[a-z]+ ([a-z])[a-z]+ ([a-z])[a-z]+ (\(.+\))$/i', '$1$2$3$4', $string);
First of all.
Create an empty variable. That will be your final result
$result="";
Then youse foreach to loop your explode string.
At every part chech the first character.
If it's not ( add the first char onto the result variable.
else add the whole array element onto the result variable
foreach(explodedString as $t){
If($t[0] !="("){$result.=$t[0];} else{$result.=$t;}
}
At the end of the loop you will get what you wanted
echo $result;

Word counter: Doesn't seem to give the output I need (PHP)

here's the line of code that I came up with:
function Count($text)
{
$WordCount = str_word_count($text);
$TextToArray = explode(" ", $text);
$TextToArray2 = explode(" ", $text);
for($i=0; $i<$WordCount; $i++)
{
$count = substr_count($TextToArray2[$i], $text);
}
echo "Number of {$TextToArray2[$i]} is {$count}";
}
So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?
I assume that you want an array with the word frequencies.
First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.
Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.
Then walk the array and increment the value of the word by one.
foreach($words as $word)
$output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
If I had understood your question correctly this should also solve your problem
function Count($text) {
$TextToArray = explode(" ", $text); // get all space separated words
foreach($TextToArray as $needle) {
$count = substr_count($text, $needle); // Get count of a word in the whole text
echo "$needle has occured $count times in the text";
}
}
$WordCounts = array_count_values(str_word_count(strtolower($text),2));
var_dump($WordCounts);

echo partial text

I want to display just two lines of the paragraph.
How do I do this ?
<p><?php if($display){ echo $crow->content;} ?></p>
Depending on the textual content you are referring to, you might be able to get away with this :
// `nl2br` is a function that converts new lines into the '<br/>' element.
$newContent = nl2br($crow->content);
// `explode` will then split the content at each appearance of '<br/>'.
$splitContent = explode("<br/>",$newContent);
// Here we simply extract the first and second items in our array.
$firstLine = $splitContent[0];
$secondLine = $splitContent[1];
NOTE - This will destroy all the line breaks you have in your text! You'll have to insert them again if you still want to preserve the text in its original formatting.
If you mean sentences you are able to do this by exploding the paragraph and selecting the first two parts of the array:
$array = explode('.', $paragraph);
$2lines = $array[0].$array[1];
Otherwise you will have to count the number of characters across two lines and use a substr() function. For example if the length of two lines is 100 characters you would do:
$2lines = substr($paragraph, 0, 200);
However due to the fact that not all font characters are the same width it may be difficult to do this accurately. I would suggest taking the widest character, such as a 'W' and echo as many of these in one line. Then count the maximum number of the largest character that can be displayed across two lines. From this you will have the optimum number. Although this will not give you a compact two lines, it will ensure that it can not go over two lines.
This is could, however, cause a word to be cut in two. To solve this we are able to use the explode function to find the last word in the extracted characters.
$array = explode(' ', $2lines);
We can then find the last word and remove the correct number of characters from the final output.
$numwords = count($array);
$lastword = $array[$numwords];
$numchars = strlen($lastword);
$2lines = substr($2lines, 0, (0-$numchars));
function getLines($text, $lines)
{
$text = explode("\n", $text, $lines + 1); //The last entrie will be all lines you dont want.
array_pop($text); //Remove the lines you didn't want.
return implode("<br>", $text); //Implode with "<br>" to a string. (This is for a HTML page, right?)
}
echo getLines($crow->content, 2); //The first two lines of $crow->content
Try this:
$lines = preg_split("/[\r\n]+/", $crow->content, 3);
echo $lines[0] . '<br />' . $lines[1];
and for variable number of lines, use:
$num_of_lines = 2;
$lines = preg_split("/[\r\n]+/", $crow->content, $num_of_lines+1);
array_pop($lines);
echo implode('<br />', $lines);
Cheers!
This is a more general answer - you can get any amount of lines using this:
function getLines($paragraph, $lines){
$lineArr = explode("\n",$paragraph);
$newParagraph = null;
if(count($lineArr) > 0){
for($i = 0; $i < $lines; $i++){
if(isset($lines[$i]))
$newParagraph .= $lines[$i];
else
break;
}
}
return $newParagraph;
}
you could use echo getLines($crow->content,2); to do what you want.

Unable to find tokens in string

I am trying to write a small php
application and i am facing a problem.
This is suppose to get text like :
this is *noun but it is *name.
And
should take the words that start with
a star and add them to the string
tokens. However this is not working.
// get list of fields (each should have words delimited by underscores
$storyArray = split(' ', $story);
$tokens = ""; // space-delimited list of fields
for ($i = 0; $i < count($storyArray); $i++) {
if ($storyArray[$i][0] == '*')
$tokens .= $storyArray[$i] + " ";
}
$tokensArray = split(' ', $tokens);
Wow, I can't believe I've been debugging this and missing the obvious fault!
This line here:
$tokens .= $storyArray[$i] + " ";
You must concatenate with a period (.), not a plus sign! What you have right now is basically the same as $tokens .= 0;
This worked for me:
$story = "this is *noun but it is *name";
$storyArray = split(' ', $story);
$tokens = array();
for ($i = 0; $i < count($storyArray); $i++) {
if ($storyArray[$i][0] == '*') {
array_push($tokens, substr($storyArray[$i], 1));
}
}
var_dump($tokens);
$tokenString = implode(" ", $tokens);
Note that I'm pushing the tokens directly into an array, then imploding it.
"+" is for addition, not string concatenation. It casts its arguments as numbers, which will always be 0 in your source.
On another note, splitting $tokens is unnecessary. Instead, append tokens to $tokensArray:
$story = "this is *noun but it is *name";
// get list of fields (each should have words delimited by underscores
$storyArray = split(' ', $story);
$tokens = ""; // space-delimited list of fields
$tokensArray=array();
for ($i = 0; $i < count($storyArray); $i++) {
if ($storyArray[$i][0] == '*') {
$tokens .= $storyArray[$i] . " ";
$tokensArray[] = $storyArray[$i];
}
}
If you only needed $tokens for generating $tokensArray, you can get rid of it. Also, depending on whether you need $storyArray, preg_match_all(...) might be able to replace your code:
preg_match_all('/\*\w+/', $story, $tokensArray);
$tokensArray = $tokensArray[0];
You can also use a regular expression to achieve the same effect, without all the string manipulation you are doing right now. This would be the most elegant solution:
$string = "this is *noun but it is *name";
// Lets set up an empty array
$tokens = array();
preg_match_all('/\*\w+/m', $string, $tokens);
$tokens = $tokens[0]; // Only one sub-pattern, dropping unnecessary dimension.
var_dump($tokens);
Regular expressions exists to do mainly exactly the kind of task you are trying to achieve now. They are usually faster than doing string manipulations manually (Regular Expression engine in PHP is compiled code).
To explain my regex:
/: start boundary
\*: an asterisk (*)
\w: any alpha-numeric character or underscore
+: previous marker, 1 or more times. (match \w one or more times)
/: end boundary
m: multiline modifier
Replace
$tokens .= $storyArray[$i] + " ";
with
$tokens .= $storyArray[$i]." ";
And
$tokensArray = split(' ', $tokens);
with
$tokensArray = split(' ', rtrim($tokens));
$tokens .= $storyArray[$i] + " ";
in this line, you should be using the . operator to concatenate strings.

Categories