How can I divide streetnr and street out of one String? - php

I want to divide an String into var street and streetnr. How can I do this with php?
The data look like:
Bakerstreet 5
Wild Street 5 a
Best Street 5a
Simplestreet
I have Streets without numbers and Streets with letters ... How can I do this?
So the street should always be like
var street = Bakerstreet, Wild Street, Best Street, Simplestreet
var streetnr should always be = 5, 5 a, 5a
My idea was to explode the string after every blank " " ... Then I reverse the array and look if the first element is just a letter. If it is, I put it into streetnr. Then I check the next element. If there are just numbers, I put it into streetnr ... and so on

I've used this as an excercise for my PHP-Training. And while I'm a huge fan of regex, I wanted to do it without em and came up with the following:
<?php
$addr = array("Bakerstreet 5",
"Wild Street 5 a",
"Best Street 5a",
"Simplestreet",
"Won't Work 47a Suite 18b",
"1st Street 10b ",
"Route 66 12a "
);
echo "<h1>Address-Parsing</h1><ol>";
foreach ($addr as $ad)
{
$no=""; // Number
$st=""; // Street
$GotNo = false;
$r = strrev(trim($ad));
echo "<li>ad=$ad";
do {
while ($r{0}=="0") {// special handling for leading "0"s (in reverted string) which are ignored by sscanf...
if (!$GotNo) $no = "0" . $no;
else $st = "0" . $st;
$r = substr($r,1);
}
$d = sscanf($r,"%d"); // get number
$s = sscanf($r,"%c"); // get string
if (is_null($d[0]) && !$GotNo) {
// no matching number and have not matched no yet - so this must be string following the nr
$no = strrev($s[0]) . $no;
$r = substr($r,strlen($s[0])); // remove match
} elseif (!$GotNo) {
$no = strrev($d[0]) . $no;
$GotNo = true;
$r = substr($r,strlen($d[0])); // remove match
} else {// we already have a number, so any text must be streetname
$st = strrev($r) . $st;
$r="";
}
if ($r !== trim($r)) {$st = " " . $st; $r = trim($r);}
} while (0<strlen($r));
$st = trim( $st);
if (empty($st)) {// might happen when no number was found...
$st=$no;
$no="";
}
echo "|st=$st|no=$no|</li>";
}
echo "</ol>";
?>

Use a regular Expression
preg_match('~^\s*(.*)\s+([0-9]+\s*[a-zA-Z]{0,1})\s*$~', $street, $match);
preg_match returns true if the street is in the right format and $match is an array containing [1]=street name, [2]=streetnr.

You could match using the following regular expression:
preg_match('/^(.+?)(?:\s+(\d.*))?$/', $street, $matches);
$street = $matches[1];
if (count($matches) == 3)
$streetnr = $matches[2];

Related

Extract and merge strings between different positions

I'm trying to make this works. I want to replace some parts of a sentence between given positions and then show the full sentence with the changes. With the following code, I'm able to make the changes but I don't know how to put together the rest of the sentence.
I have two arrays, one with the positions where a woman name appears and another one with men names. The code replaces the pronoun "his" by "her" when a woman is before a man between the intervals. The last thing I need is to reconstruct the sentence with the changes made but I don't know how to extract the rest of the sentence (the result, in the example, is from positions 0 to 20 (Maria her dress but) and 36 to 51 (Lorena her dog) but I need to extract from 20 to 36 (Peter his jeans) and 51 to the end (Juan his car) to merge them in their positions).
The result should be: "Maria her dress but Peter his jeans Lorena her dog Juan his car". I'll appreciate any help with this, I've been looking for other similar questions but I found nothing.
<?php
$womenpos = array("0","36"); //these arrays are just examples of positions
$menpos = array("20","51"); //they will change depending on the sentence
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
foreach ($womenpos as $index => $value) {
$value2 = $menpos[$index];
if($value < $value2) {
echo "\nWoman(" . $value . ") is before man(" . $value2 . ")\n";
$end = ($value2 - $value);
$improved = str_replace(' his ', ' her ',
substr($sentence, $value, $end));
echo $improved."\n";
} else {
$improved = "Nothing changed";
echo $improved;
}
}
Ok, how about this:
$womenpos = array("0","36");
$menpos = array("20","51");
$bothpos = array_merge($womenpos,$menpos);
sort ($bothpos);
print_r($bothpos);
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
for ($i = 0; $i<sizeof($bothpos); $i++) {
$start = $bothpos[$i];
if ($i ==sizeof($bothpos)-1) {
$end = strlen($sentence);
}
else {
$end = $bothpos[$i+1];
}
$length = $end-$start;
$segment = substr($sentence, $start, $length);
if (in_array($start, $womenpos)) {
$new_segment = str_replace (' his ', ' her ', $segment);
}
else { $new_segment = $segment; }
$improved .= $new_segment;
print "<li>$start-$end: $segment : $new_segment </li>\n";
}
print "<p>Improved: $improved</p>";
This combines the men's and women's position arrays to consider each stretch of text as one that might have an error. If that stretch of text starts at one of the womenpos points, then it changes 'his' to 'her'. If not it leaves it alone.
Does this get you in the direction you want to go in? I hope so!
This approaches the problem differently, but I wonder if it would provide the solution you're looking for:
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
$women = array ("Maria", "Lorena");
$words = explode (" ", $sentence);
for ($i=0; $i< sizeof($words); $i++) {
if ($words[$i] == "his" && in_array($words[$i-1], $women)) {
$words[$i] = "her";
}
}
print (join(" ", $words));
This goes through the words one at a time; if the preceding word is in the $women array and the current word is "his", it changes the word to "her". Then it spits out all the words in order.
Does this do what you need, or do you really want a complex string positioning answer?

I would like to be able to generate a fill in the blank from a word missing 2 letters randomly

$word = "superman";
I would like to be able to randomly choose 2 letters from what ever word is in $word and build a fill in the blank box for me to be able to answer
example some how random picks the p and the a
su_erm_n comes up so I would fill in the first box with p and the second one with a I guess with a form
$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n";
if ($wordfinshed == $word) {
echo "congrats";
}
else{
echo "try again";
}
I am just learning php I have some things that I have done that are very complicated but was having a hard time with the random stuff any help would help me learn this
You can use PHP's rand() function to select a random number from 0 to the length of the word you are modifying and change the character at that index to something else
For example:
$str = "superman";
$str[rand(0, strlen($str)-1)] = "_";
Assuming that the rand() function output a value of 3 for example, we'd end up with this output:
sup_rman
We can put this in a function that can be called more than once in order to make more than one blank space in the word:
function addBlank($str){
do{
$index = rand(0, strlen($str)-1);
$tmp = $str[$index];
$str[$index] = "_";
} while($tmp =! "_");
return $str;
}
This function accepts a string and after each call will replace a letter in the string with _. Each call will result in one more blank space. The variable $tmp holds the value of the string at the randomly chosen index and checks that it wasn't already a blank space, and if it was, it picks another index to try to replace.
So to put this in practice, we can call the above function multiple times and store the result back into a variable, here is example output:
$str = addBlank("superman");
//the value of $str is now sup_rman
$str = addBlank($str)
//the value of $str is now sup_r_an
$word = "superman";
$size = strlen($word) -1;
$fillinblank1 = $word[rand(0,$size)];
$fillinblank2 = $word[rand(0,$size)];
$wordfinished = "su" . $fillinblank1 . "erm" . $fillinblank2 . "n";
echo $wordfinished;
Output:
sueermun
Demo
http://ideone.com/Z66xsI

regex for extracting hash tags without spaces

I'm using this:
$t = "#hashtag #goodhash_tag united states #l33t this";
$queryVariable = "";
if(preg_match_all('/(^|\s)(#\w+)/', $t, $arrHashTags) > 0){
array_filter($arrHashTags);
array_unique($arrHashTags);
$count = count($arrHashTags[2]);
if($count > 1){
$counter = 1;
foreach ($arrHashTags[2] as $strHashTag) {
if (preg_match('/#\d*[a-z_]+/i', $strHashTag)) {
if($counter == $count){
$queryVariable .= $strHashTag;
} else{
$queryVariable .= $strHashTag." and ";
}
$newTest = str_replace($arrHashTags[2],"", $t);
}
$counter = $counter + 1;
}
}
}
echo $queryVariable."<br>"; // this is list of tags
echo $newTest; // this is the remaining text
The output based on the $t above is:
#hashtag and #goodhash_tag and #l33t
united states this
First problem:
if $t = '#hashtag#goodhash_tag united states #l33t this'; i.e without space between two tags, the output becomes:
#hashtag and #l33t
#goodhash_tag united states this
Second problem:
if $t = '#hashtag #goodhash_tag united states #l33t this #123'; i.e with an invalid tag #123 it somehow disturbs my list of tags extracted in $queryVariable like the output becomes
#hashtag and #goodhash_tag and #l33t and // note the extra 'and'
united states this
Please help on these two if anyone?
Instead of using so many comparisions etc. for your regex. You can simply have the following:
$t = "#hashtag #goodhash_tag united states #l33t this #123#tte#anothertag sth";
$queryVariable = "";
preg_match_all('/(#[A-z_]\w+)/', $t, $arrHashTags);
print_r( $arrHashTags[1] );
To get them as string with and joining them, you can use implode.
$queryVariable = implode( $arrHashTags[1], " and " );
For the remaining text, you can have preg_replace or str_replace(whichever you are comfortable with).
Here is the codepad link.

PHP regex vs explode() for phone number

I have been messing around with some regular expressions, and I ran into a small hiccup with a more complicated version of my phone number formatting.
Here's what I am working with:
$number1 = '+1 (123) 1234567';
$number1 = '+966 (1) 1234567 x555';
These strings are actually being output from the MySQL query I created, and I love it.
However, I'm making a simple php function to auto-format the subscribers number from 1234567 to 123-4567.
I'm not too concerned about any number that doesn't start with +1. So I'm formatting US and Canadian numbers.
Here's what I attempted, if there was only 7 digits, and if the string starts with +1
<?php
function format_phonenumbers($phone){
if(empty($phone)){ return ''; }
$exploded = explode(' ',$phone);
$countrycode = $exploded[0];
$areacode = $exploded[1];
$number = $exploded[2];
$ext = (!empty($exploded[3])?$exploded[3]:'');
if($countrycode=='+1'){
$strphone = strlen($number);
if ($strphone == 7) { // auto-format US PHones
$prefix = substr($number,0,3);
$suffix = substr($number,-4);
}
$phone = $countrycode.' '.$areacode.' '.$prefix.'-'.$suffix.' '.$ext;
}
return $phone;
}
echo format_phonenumbers('+1 (714) 1234567'); // US domestic
echo '<br>';
echo format_phonenumbers('+966 (1) 1234567 x555'); // international
?>
This formats what I need, but I'm curious if anyone believes I can do this in a better way. Like using a regex checker, that finds anything after the parenthesis, but before an extension, rather than using the explode() function.
Something like:
function format_phonenumbers($phone)
{
return preg_replace_callback(
'/([)]\s*)(\d{3,3}(\d+)/',
function ($match) {
return $match[1] . $match[2] . '-' . $match[3];
},
$phone
);
}
This should work, but requires PHP 5.3.0 or higher (if not you'll have to use create_function). Its arguable if it is any better however.

PHP Word Length Density / Count calc for a string

Given a text, how could I count the density / count of word lengths, so that I get an output like this
1 letter words : 52 / 1%
2 letter words : 34 / 0.5%
3 letter words : 67 / 2%
Found this but for python
counting the word length in a file
Index by word length
You could start by splitting your text into words, using either explode() (as a very/too simple solution) or preg_split() (allows for stuff that's a bit more powerful) :
$text = "this is some kind of text with several words";
$words = explode(' ', $text);
Then, iterate over the words, getting, for each one of those, its length, using strlen() ; and putting those lengths into an array :
$results = array();
foreach ($words as $word) {
$length = strlen($word);
if (isset($results[$length])) {
$results[$length]++;
}
else {
$results[$length] = 1;
}
}
If you're working with UTF-8, see mb_strlen().
At the end of that loop, $results would look like this :
array
4 => int 5
2 => int 2
7 => int 1
5 => int 1
The total number of words, which you'll need to calculate the percentage, can be found either :
By incrementing a counter inside the foreach loop,
or by calling array_sum() on $results after the loop is done.
And for the percentages' calculation, it's a bit of maths -- I won't be that helpful, about that ^^
You could explode the text by spaces and then for each resulting word, count the number of letters. If there are punctuation symbols or any other word separator, you must take this into account.
$lettercount = array();
$text = "lorem ipsum dolor sit amet";
foreach (explode(' ', $text) as $word)
{
#$lettercount[strlen($word)]++; // # for avoiding E_NOTICE on first addition
}
foreach ($lettercount as $numletters => $numwords)
{
echo "$numletters letters: $numwords<br />\n";
}
ps: I have not proved this, but should work
You can be smarter about removing punctuation by using preg_replace.
$txt = "Sean Hoare, who was first named News of the World journalist to make hacking allegations, found dead at Watford home. His death is not being treated as suspiciou";
$txt = str_replace( " ", " ", $txt );
$txt = str_replace( ".", "", $txt );
$txt = str_replace( ",", "", $txt );
$a = explode( " ", $txt );
$cnt = array();
foreach ( $a as $b )
{
if ( isset( $cnt[strlen($b)] ) )
$cnt[strlen($b)] += 1;
else
$cnt[strlen($b)] = 1;
}
foreach ( $cnt as $k => $v )
{
echo $k . " letter words: " . $v . " " . round( ( $v * 100 ) / count( $a ) ) . "%\n";
}
My simple way to limit the number of words characters in some string with php.
function checkWord_len($string, $nr_limit) {
$text_words = explode(" ", $string);
$text_count = count($text_words);
for ($i=0; $i < $text_count; $i++){ //Get the array words from text
// echo $text_words[$i] ; "
//Get the array words from text
$cc = (strlen($text_words[$i])) ;//Get the lenght char of each words from array
if($cc > $nr_limit) //Check the limit
{
$d = "0" ;
}
}
return $d ; //Return the value or null
}
$string_to_check = " heare is your text to check"; //Text to check
$nr_string_limit = '5' ; //Value of limit len word
$rez_fin = checkWord_len($string_to_check,$nr_string_limit) ;
if($rez_fin =='0')
{
echo "false";
//Execute the false code
}
elseif($rez_fin == null)
{
echo "true";
//Execute the true code
}
?>

Categories