Extracting phrases from text strings - php

Please I need to use php to extract phrases from a text shown below:
Peter,
please check your email for a document I sent, thanks.
Mark,
please I need you to fix my Toyota Camry, thanks.
Mark,
please go and pick up the kids from school, thanks.
Jane,
please go the shop and some items for the house, thanks.
What I need is to display only the phrases relating to Mark. Please note that in this example, Mark has only 2 messages and it could be more residing between Peter and Jane
<?php
$data = "
Peter, <br>
please check your email for a document I sent, thanks.<br>
Mark, <br>
please I need you to fix my Toyota Camry, thanks. <br>
Mark, <br>
please go and pick up the kids from school, thanks. <br>
Jane, <br>
please go the shop and some items for the house, thanks.
";
$start = 'Mark';
$end = 'thanks';
$startIndex = strpos($data, $start);
$endIndex = strpos($data, $end, $startIndex) + strlen($end);
$result = substr($data, $startIndex, $endIndex - $startIndex);
echo $result;
?>
This is what I tried but the result was only the first Phrase
Mark, Please I need to fix my Toyota Camry, thanks.
But I need it to show the second or more phrases relating to Mark.
Please I need help to achieve this.
For this example I am expecting as follows:
Mark, Please I need you to fix my Toyota Camry, thanks. Mark, Please
go and pick up the kids from school, thanks.

Using a while loop to keep going, until the strpos to determine the start index returns false:
$start = 'Mark';
$end = 'thanks';
$fromPos = 0;
while(false !== ($startIndex = strpos($data, $start, $fromPos))) {
$endIndex = strpos($data, $end, $startIndex) + strlen($end);
$result = substr($data, $startIndex, $endIndex - $startIndex);
$fromPos = $endIndex; // set the new position to search from
// on the next iteration
echo $result ."<br><br>";
}

You can explode your string by <br> and search every two items for the key and append the next if found.
$input = explode("<br>", $yourtext);
$searchTerm = 'Mark,';
$output = [];
for ($index = 0; $index < count($input); $index += 2) {
if (strpos($input[$index], $searchTerm) !== false) {
if (isset($input[$index + 1])) $output[]=$input[$index + 1];
}
}

Related

php regex matching issue

I have this kind of output:
1342&-4&-6
And it could be more times or less:
1342&-4 (I need to replace it with: 1342,1344)
1340&-1&-3&-5&-7 (I need to replace it with: 1340,1341,1343,1345,1347)
I've tried to use preg_match but with no success,
Can someone help me with that?
Thanks,
<?php
//so if you had sting input of "1342&-4" you would get 2 stings returned "1342" and "1344"?
//1340&-1&-3&-5&-7 --> 1340 and 1341 and 1343 and 1345 and 1347
//$str="1342&-4";
$str="1340&-1&-3&-5&-7";
$x=explode('&-',$str);
//print_r($x);
foreach ($x as $k=> $v){
if($k==0){
//echo raw
echo $v."<br>";
}else{
//remove last number add new last number
echo substr($x[0], 0, -1).$v."<br>";
}
}
output:
13401341134313451347
i used <br> you can use what ever you need or add to a new variable(array)
$array = explode('&-', $string);
$len = count($array);
for($i=1; $i<$len; $i++)
$array[$i] += $array[0] / 10 * 10;
var_dump(implode(' ', $array));

reorder / rewrap bbcodes

I'm trying to reorder the BBCodes but I failed
so
[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶b̶]̶[̶/̶u̶]̶[̶/̶i̶]̶ ̶-̶ ̶w̶r̶o̶n̶g̶ ̶o̶r̶d̶e̶r̶ ̶ ̶
I̶ ̶w̶a̶n̶t̶ ̶i̶t̶ ̶t̶o̶ ̶b̶e̶:̶ ̶
̶[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶u̶]̶[̶/̶i̶]̶[̶/̶b̶]̶ ̶-̶ ̶r̶i̶g̶h̶t̶ ̶o̶r̶d̶e̶r̶
PIC:
I tried with
<?php
$string = '[b][i][u]foo[/b][/u][/i]';
$search = array('/\[b](.+?)\[\/b]/is', '/\[i](.+?)\[\/i]/is', '/\[u](.+?)\[\/u]/is');
$replace = array('[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]');
echo preg_replace($search, $replace, $string);
?>
OUTPUT: [b][i][u]foo[/b][/u][/i]
any suggestions ? thanks!
phew, spent awhile thinking of the logic to do this. (feel free to put it in a function)
this only works for the scenario given. Like other users have commented it's impossible. You shouldn't be doing this. Or even on server side. I'd use a client side parser just to throw a syntax error.
supports [b]a[i]b[u]foo[/b]baa[/u]too[/i]
and bbcode with custom values [url=test][i][u]foo[/url][/u][/i]
Will break with
[b] bold [/b][u] underline[/u]
And [b] bold [u][/b] underline[/u]
//input string to be reorganized
$string = '[url=test][i][u]foo[/url][/u][/i]';
echo $string . "<br />";
//search for all opentags (including ones with values
$tagsearch = "/\[([A-Za-z]+)[A-Za-z=._%?&:\/-]*\]/";
preg_match_all($tagsearch, $string, $tags);
//search for all close tags to store them for later
$closetagsearch = "/(\[\/([A-Za-z]+)\])/is";
preg_match_all($closetagsearch, $string, $closetags);
//flip the open tags for reverse parsing (index one is just letters)
$tags[1] = array_reverse($tags[1]);
//create temp var to store new ordered string
$temp = "";
//this is the last known position in the original string after a match
$last = 0;
//iterate through each char of the input string
for ($i = 0, $len = strlen($string); $i < $len; $i++) {
//if we run out of tags to replace/find stop looping
if (empty($tags[1]) || empty($closetags[1]))
continue;
//this is the part of the string that has no matches
$good = substr($string, $last, $i - $last);
//next closing tag to search for
$next = $closetags[1][0];
//how many chars ahead to compare against
$scope = substr($string, $i, strlen($next));
//if we have a match
if ($scope === "$next") {
//add to the temp variable with a modified
//version of an open tag letter to become a close tag
$temp .= $good . substr_replace("[" . $tags[1][0] . "]", "/", 1, 0);
//remove the first key/value in both arrays
array_shift($tags[1]);
array_shift($closetags[1]);
//update the last known unmatched char
$last += strlen($good . $scope);
}
}
echo $temp;
Please also note: it might be the users intention to nest the tags out of order :X

Multiple search word matching using strpos

I wonder if anyone can help with a little problem I can't seem to fix - my
head is going round in circles at the moment...
Ok I have a .txt file with numerous lines of info - I am trying to match keywords
with those lines and display a certain number of the matching lines.
I put together this bit of script and whilst it works it only matches a line if the
words are in the same order as the search words.
At the moment as an example:
Search words:
red hat
Lines in .txt file:
this is my red hat
my hat is red
this hat is green
this is a red scarf
your red hat is nice
As the script is at the moment it will match and display lines 1, 5
However I would like it to match and display lines 1, 2, 5
Any order but all words must be present to match.
I have looked through loads of postings here and elsewhere and I understand that
what is needed is to explode the string and then search for each word in a loop but
I cannot get that to work, despite trying a few different ways as it just returns the
same line numerous times.
Any help would be appreciated before I lose what hair I have left :-)
Here is the code I have working at present - the search variable is already
set:
<?php
rawurldecode($search);
$search = preg_replace('/[^a-z0-9\s]|\n|\r/',' ',$search);
$search = strtolower($search);
$search = trim($search);
$lines = file('mytextfile.txt') or die("Can't open file");
shuffle($lines);
$counter = 0;
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false AND $counter <= 4)
{
$found = true;
$line = '<img src=""> '.$line.'<br>';
echo $line;
$counter = $counter + 1;
}
}
// If the text was not found, show a message
if(!$found)
{
echo $noresultsmessage;
}
?>
Thanks in advance for any help - still learning :-)
Here's my code:
$searchTerms = explode(' ', $search);
$searchCount = count($searchTerms);
foreach($lines as $line)
{
if ($counter <= 4) {
$matchCount = 0;
foreach ($searchTerms as $searchWord) {
if (strpos($line, $searchWord) !== false ) {
$matchCount +=1;
} else {
//break out of foreach as no need to check the rest of the words if one wasn't found
continue;
}
}
if ($matchCount == $searchCount) {
$found = true;
$line = '<img src=""> '.$line.'<br>';
echo $line;
$counter = $counter + 1;
}
}
}

How do I insert a string after every 50 words using php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I have to insert a <br> tag after every 52 words so that it displays a line break otherwise the paragraph keeps going on and on increasing its width rather that the height. If there is any other, better way, please tell me.
My code
<?php
$str = "Hello world. My name is Yash Mathur and I am a student.
I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com
to seek for an answer. Please help me insert a line break after every 52 characters.
Thanks in advance!";
$len = strlen($str);
if ($len > 52) {
$str = substr($str, 0, 52) . "<br>";
}
echo $str;
?>
I need to somehow put this in a loop to insert the <br> tag every 52 characters.
I assume what you are trying to achieve in the end, is just a decent-looking paragraph, whose line-length is not too long, as to become hard to read. I believe this is a cosmetic issue, that can be better addressed in the presentation layer of your application, i.e. the style sheet.
In the style belonging to the paragraph, you could just add a "width:250px" (250px is an arbitrary value) to constrain the text into a self-wrapping box that is defined by the width of the paragraph.
I would not do it in PHP unless there is a really valid reason for this, because, if you ever need to change the look of your paragraph, you would then have to delve into your PHP code. This might seem trivial now, but in a couple months you probably will not even remember writing such code in the first place. This will lead to a minor headache at best, and a great deal of wasted time searching for just this formatting function.
Please rethink your strategy.
Try using the following code:
$original = "some long string";
$parts = str_split($original, 50);
$final = implode("<br>", $parts);
You could try something like this. But this doesn't check if you're splitting a line in the middle of a word and you'll end up with an ugly output. Try using CSS instead :)
<?php
$str = "Hello world. My name is Yash Mathur and I am a student. I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com to seek for an answer. Please help me insert a line break after every 52 characters. Thanks in advance!";
for ($i = 0; $i < mb_strlen($str); $i++) {
if ($i % 52){
echo mb_substr($str, 0 , 52) . '<br />';
$str = mb_substr($str, 52, mb_strlen($str));
}
}
?>
This should do the trick:
$string='Lorem ipsum...';
$parts=explode(' ',$string);
$result='';
foreach ($parts as $key=>$part)
{
$result.=$part.' ';
if ($key%50==49)
$result.='<br>';
}
However better way is to use wordwrap()
$original = "Hello world. My name is Yash Mathur and I am a student.
I need help in this question as this is getting on my nerves, so I came to
stackoverflow.com
to seek for an answer. Please help me insert a line break after every 52 characters.
Thanks in advance!";
$parts = mb_split("\s", $original);
$final = "";
$newLineCount = 10;
$wordsCount = 0;
foreach ($parts as $part) {
if($wordsCount < $newLineCount){
$final = $final . " ". $part;
$wordsCount +=1;
}else{
$final = $final . "<br>". $part;
$wordsCount = 0;
}
}
echo $final ;
output:

PHP Regex to Find Any Number at the Beginning of String

I'm using PHP, and am hoping to be able to create a regex that finds and returns the street number portion of an address.
Example:
1234- South Blvd. Washington D.C., APT #306, ZIP45234
In the above example, only 1234 would be returned.
Seems like this should be incredibly simple, but I've yet to be successful. Any help would be greatly appreciated.
Try this:
$str = "1234- South Blvd. Washington D.C., APT #306, ZIP4523";
preg_match("~^(\d+)~", $str, $m);
var_dump($m[1]);
OUTPUT:
string(4) "1234"
I know you requested regex but it may be more efficient to do this without (I haven't done benchmarks yet). Here is a function that you might find useful:
function removeStartInt(&$str)
{
$num = '';
$strLen = strlen($str);
for ($i = 0; $i < $strLen; $i++)
{
if (ctype_digit($str[$i]))
$num .= $str[$i];
else
break;
}
if ($num === '')
return null;
$str = substr($str, strlen($num));
return intval($num);
}
It also removes the number from the string. If you do not want that, simply change (&$str) to ($str) and remove the line: $str = substr($str, strlen($num));.

Categories