How to detect more than one line break \n in PHP? - php

I need to detect more than one \n. Doesn't matter if it's 2 or 1000, as long as it's more than one \n. What would be the regex for this (if regex is necessary that is)?
EDIT
I am using this:
$pregmatch = preg_match('#\\n\\n+#', $locations);
if ($pregmatch > 0) {
echo 'more than one, this many: '.count($pregmatch);
} else
echo 'less than one';
but count($pregmatch) doesn't return the actual number of more than one \n detected. How can that be achieved?

Are you looking for more than 1 \n in general? if so:
if (preg_match_all('#\\n#', $string, $matches) > 1) {
//More than 1 \n
}
Or without regex:
if (substr_count($string, "\n") > 1) {
//More than 1 \n
}
Or even (but it's far less efficient):
$chars = count_chars($string);
if (isset($chars[ord("\n")]) && $chars[ord("\n")] > 1) {
//More than 1 \n
}
If in a row:
if (preg_match_all('#\\n\\n+#', $string, $matches) > 0) {
//More than 1 \\n in a row
}
Edit: So, based on your edit, I can summize two possibilities about what you want to know.
If you want to know the number of \n characters in a row (more than 1), you could do:
if (preg_match('#\\n\\n+#', $string, $match)) {
echo strlen($match[0]) . ' Consecutive \\n Characters Found!';
}
Or, if you wanted to know for each occurance:
if (preg_match_all('#\\n\\n+#', $string, $matches)) {
echo count($matches) . ' Total \\n\\n+ Matches Found';
foreach ($matches[0] as $key => $match) {
echo 'Match ' . $key . ' Has ' .
strlen($match) . ' Consecutive \\n Characters Found!';
}
}

Something like (doc):
preg_match_all("[\n]*", $yourString, $outArray)
preg_match_all will return a count of how many there were, as well as the matches in the outArray.

You need to provide the /m modifier so that the scan spans more than on line:
if (preg_match('/\n\n/m', $str)) {
echo "match";
} else {
echo "no match";
}

You can avoid using regex, saving CPU, here is an elegant and tricky way:
$text_parts = explode("\n", $original_string);
Now you can join it replacing line breaks with something elese:
$new_string = implode("<br />", $text_parts);
I hope this helps

Related

Check if hashtag is at the start OR middle of string php

I'm currently grabbing all #hashtags found in a string (i.e. a tweet). Works as it should.
However, I want to find hashtags that are only at the start of the string OR in the MIDDLE of the string (or close enough to it). In other words, find all hashtags that aren't at the end of the string.
Bonus points, if you can also point me in the direction on how to see if a hashtag exists at the end of the string as well.
$tweet = 'This is an #example tweet';
preg_match_all('/(#\w+)/u', $tweet, $matches);
if ($matches) { // found hashtag(s) }
// Check if Hashtag is last word; the strpos and explode way:
$tweet = 'This is an #example #tweet';
$words = explode(" ", $tweet);
$last_word = end($words);
// count the number of times "#" occurs in the $tweet.
// if # exists in somewhere else $exists_anywhere equals TRUE !!
$exists_anywhere = substr_count($tweet,'#') > 1 ? TRUE : FALSE ;
if(strpos($last_word,'#') !== FALSE ) {
// last word has #
}
from doc :
Do not use preg_match() if you only want to check if one string is
contained in another string. Use strpos() or strstr() instead as they
will be faster.
preg_match_all('/(?!#\w+\W+$)(#\w+)\W/', $tweet, $result);
This is a #tweet folks will catch #tweet
#Second example of #tweet folks will catch #Second and #tweet
#Another example of #tweet will catch #Another but not #tweet (even if it ends in !, ., or any other non-word character)
We're almost done, #yup! won't catch anything
Last one #tweet! good night will catch #tweet
Of course, all your hastags (captures) will be stored in $result[1]
To match at the beginning only:
/^(#\w+)/
To look for a specific #hashtag:
/^#tweet/
To match anywhere in the middle (not beginning or end):
/^[^#]+(#\w+)[^\w]+$/
To look for a specific #hashtag:
/^[^#]+#tweet[^\w]$/
To match at the end only:
/(#\w+)$/
To look for a specific #hashtag:
/#tweet$/
OK, personally I would turn the string into an array of words:
$words = explode(' ', $tweet);
Then run a check on the first word:
preg_match_all('/(#\w+)/u', $words[0], $matches);
if ($matches) {
//first word has a hashtag
}
Then you can simply walk through rest of array for hashtags in the middle.
And finally to check the last word,
$sizeof = count($words) - 1;
preg_match_all('/(#\w+)/u', $word[$sizeof], $matches);
if ($matches) {
//last word has a hashtag
}
UPDATE / EDIT
$tweet = "Hello# It's #a# beaut#iful day. #tweet";
$tweet_arr = explode(" ", $tweet);
$arrCount = 0;
foreach ($tweet_arr as $word) {
$arrCount ++;
if (strpos($word, '#') !== false) {
$end = substr($word, -1);
$beginning = substr($word, 0, 1);
$middle_string = substr($word, 1, -1);
if ($beginning === "#") {
echo "hash is at the beginning on word " . $arrCount . "<br />";
}
if (strpos($middle_string, '#') !== false) {
$charNum = strpos($middle_string, '#') + 1;
echo "hash is in the middle at character number " . $charNum . " on word " . $arrCount . "<br />";
}
if ($end === "#") {
echo "hash is at the end on word " . $arrCount . "<br />";
}
}
}

Find exact string inside a string

I have two strings "Mures" and "Maramures". How can I build a search function that when someone searches for Mures it will return him only the posts that contain the "Mures" word and not the one that contain the "Maramures" word. I tried strstr until now but it does now work.
You can do this with regex, and surrounding the word with \b word boundary
preg_match("~\bMures\b~",$string)
example:
$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
echo "matched";
else
echo "no match";
Use preg_match function
if (preg_match("/\bMures\b/i", $string)) {
echo "OK.";
} else {
echo "KO.";
}
How do you check the result of strstr? Try this here:
$string = 'Maramures';
$search = 'Mures';
$contains = strstr(strtolower($string), strtolower($search)) !== false;
Maybe it's a dumb solution and there's a better one. But you can add spaces to the source and destination strings at the start and finish of the strings and then search for " Mures ". Easy to implement and no need to use any other functions :)
You can do various things:
search for ' Mures ' (spaces around)
search case sensitive (so 'mures' will be found in 'Maramures' but 'Mures' won't)
use a regular expression to search in the string ( 'word boundary + Mures + word boundary') -- have a look at this too: Php find string with regex
function containsString($needle, $tag_array){
foreach($tag_array as $tag){
if(strpos($tag,$needle) !== False){
echo $tag . " contains the string " . $needle . "<br />";
} else {
echo $tag . " does not contain the string " . $needle;
}
}
}
$tag_array = ['Mures','Maramures'];
$needle = 'Mures';
containsString($needle, $tag_array);
A function like this would work... Might not be as sexy as preg_match though.
The very simple way should be similar to this.
$stirng = 'Mures';
if (preg_match("/$string/", $text)) {
// Matched
} else {
// Not matched
}

Cannot read the first letter

I want to add a function to return whether the first letter is a capital or not from my last question.
Here's the code:
<?php
function isCapital($string) {
return $string = preg_match('/[A-Z]$/',$string{0});
}
$text = " Poetry. do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text); $save = array();
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save[] = $sentence. ".";
}
}
if( count( $save) > 0) {
foreach ($save as $nama){
if (isCapital($nama)){
print_r ($nama);
}
}
}
?>
The result should be...
Poetry can be divided into several genres, or categories.
...but it prints nothing. I need only the sentence that consists of more than 6 words and start with capital letter.
When you do the explode() function, you are leaving a space at the start of the string, which means that the leftmost character of $string will never be a capital letter--it will be a space. I would change the isCapital() function to the following:
function isCapital($string) {
return preg_match('/^\\s*[A-Z]/', $string) > 0;
}
You should be able to accomplish all of this through one regular expression, if you're so inclined:
preg_match_all('/((?=[A-Z])([^\s.!?]+\s+){5,}[^\s.!?]+[.!?])/', $string, $matches);
http://refiddle.com/2hz
Alternatively, remove the ! and ? from the character classes to only count . as a sentence delimiter.

PHP preg_match meaning and issue

Currently I have this code:
<?php
if (isset($_GET['id'])) {
$itemid = $_GET['id'];
$search = "$itemid";
$query = ucwords($search);
$string = file_get_contents('http://clubpenguincheatsnow.com/tools/newitemdatabase/items.php');
if($itemid=="")
{
echo "Please fill out the form.";
}
else
{
$string = explode('<br>',$string);
foreach($string as $row)
{
preg_match('/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
if(strstr($matches[1], $query))
{
echo "<a href='http://clubpenguincheatsnow.com/tools/newitemdatabase/info.php?id=$matches[2]'>";
echo $matches[1];
echo "</a><br>";
}
}
if($matches[1]=="")
{
echo "Item does not exist!";
}
}
}
else {
echo "Item does not exist!";
}
?>
What I want to know is what does this section mean? preg_match('/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches); mainly the /^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/ part is what I am wondering about.
Also, an issue that I have been having is how can I allow it to use numbers too? Because I have another file that has the data (http://clubpenguincheatsnow.com/tools/newitemdatabase/items.php) and it want it to grab everything, even the names with the numbers.
How do I do this though? Please help me! Any help would be VERY HIGHLY appreciated!
That is a regular expression.
The '^' matches the beginning of a string.
The '\D' matches any character that is not a digit.
The '\d' matches any digit.
The '\s' matches any whitespace.
The plus sign means that the previous character can occur multiple times.
So basically it would match all those lines in your file, except that last comma.
Blue = 1 = No = 20
That line would match the regex.
About your last question to allow numbers too, use this:
/^(.+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/
the code is a regular expression:
/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/
the code will use the regular expression to cut the string um pieces and put in an array ($matches)
preg_match('/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
You shall use the code to see better
print_r($matches)
To find by name or by item number change the code
if(strstr($matches[1], $query))
to
if(isset($matches[1]) && (strstr($matches[1], $query) || $matches[2] == $query) )
Your code shall look like this...
if (isset($_GET['id'])) {
$itemid = $_GET['id'];
$search = "$itemid";
$query = ucwords($search);
$string = file_get_contents('http://clubpenguincheatsnow.com/tools/newitemdatabase/items.php');
if($itemid=="")
{
echo "Please fill out the form.";
}
else
{
$string = explode('<br>',$string);
foreach($string as $row)
{
preg_match('/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/', trim($row), $matches);
if(isset($matches[1]) && (strstr($matches[1], $query) || $matches[2] == $query) )
{
echo "<a href='http://clubpenguincheatsnow.com/tools/newitemdatabase/info.php?id=$matches[2]'>";
echo $matches[1];
echo "</a><br>";
}
}
}
}
else {
echo "Item does not exist!";
}
/^(\D+)\s=\s(\d+)\s=\s(\D+)\s=\s(\d+)/
This regular expression will match any number of non-numeric character, followed by a whitespace character, followed by equals, and so on. For example, this
asd = 1 = yh = 23
To allow numbers in the names:
/^(\w+)\s=\s(\d+)\s=\s(\w+)\s=\s(\d+)/
To allow numbers and alpha-numeric chars in everything:
/^(\w+)\s=\s(\w+)\s=\s(\w+)\s=\s(\w+)/
To include spaces and ' too:
/^([\w\s']+)\s=\s([\w\s']+)\s=\s([\w\s']+)\s=\s([\w\s']+)/
The code, as said by Sena, is a regular expression. It is capturing four groups with "=" in between them.
group 1: (\D+) : any character that is not a digit one or more times
group 2: (\d+) : any character that is a digit one or more times
group 3: (\D+) : same as one
group 4: (\d+) : same as two.
So, it will match something like this: a = 1 = bc = 2
So, it is matching numbers, what do you want it to do? try print_r($matches) as suggested above.

How can I replace spaces with carriage returns using PHP?

I have a few strings
Computer Stations
Monitors
Indian Reserve
How do i replace spaces in a variable with carriage returns "\r"? How can I determine if a replacement was made so I can add a CSS class in my output.
My PHP is below and basically for CSS purposes i need to force a carriage return on two words and if the string is a single word then give the class "single" so i can style it differently...any ideas
$key "Computer Stations"
echo "<li>{$key}</li>";
$key "Monitors"
echo "<li>{$key}</li>";
$key "Indian Reserve"
echo "<li>{$key}</li>";
If I understand you correctly:
if (strpos($str, ' ') !== false) {
// there is space in string, do something
}
If you want to replace space to something:
str_replace(' ', "\n", $string);
In this case str_replace replaces every space to newline symbol.
Following code will replace all spaces with return symbol ("\r") and if there isn't any, set variable $class to "single".
$newString = str_replace(" ", "\r", $oldString, $count);
if($count == 0) {
$class = "single";
}
echo "<li><a class=\"$class\">$newString</a></li>";
By return you mean newline? If so, you should use "\n" instead of "\r". If you would like to see the newline in a browser not just in the code you should use '<br />' instead.
To check presence of any string inside another, use the PHP strpos() function:
if (strpos($key, " ") !== FALSE) {
// There is a space
}
else {
// No space in string
}

Categories