I've been working on this for a while and I can't seem to figure it out. I know it must be something really simple. Basically I have a script that works as a program that translates English to Piglatin, and it works fine, but I want the user to have a choice of whether or not to actually operate that script, by using a radio form with the text input that says "English" or "Piglatin". I've tried all different ways to get this to work, but using a nested conditional seems like it would be the most logical answer to me. However, whenever I try to run the script with it, it doesn't work. Can someone please tell me what I'm doing wrong?! It would be much appreciated. Thanks!
HTML Form:
<p><input type="text" name="original" size="20" maxlength="40" /></label></p>
<p><input type="radio" name="english" value="yes"/>english <input type="radio" name="english" value="no"/>piglatin</p>
<input type="submit" name="submit" value="submit" /></form>
PHP:
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
}
elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
}
else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
else
{echo $original.".";
};
?>
Like I said, I'm sure it's something really small and simple that I just can't see because I've been looking at the code so long. Any help is appreciated! Thank you!
Sort your indentation out and you will see your missing closing brackets.
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
$piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
} elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
} else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
} else {
echo $original.".";
};
Related
I am trying to scrape an ebay page such as this one: http://www.ebay.co.uk/sch/Cars-/9801/i.html?_nkw=vw+golf
Everything works great except one of my regular expressions just isn't matching the content and therefore the matches aren't being pushed to $linksArray I have outputted the contents to make sure what I am trying to match is infact there - and it is. I then go print_r($linksArray) where all the matches should be. but it's not. It is an empty multi dimensional array. You can see my live example here: http://www.mycommunity.co.za/marcksack/index.php
Here is my PHP code:
<?php
echo '<form method="POST">
<input type="text" id="url" name="url" size="120" value="' . (isset($_REQUEST["url"]) && !empty($_REQUEST["url"]) ? $_REQUEST["url"] : "") . '"/>
<input type="submit" value="Submit" />
</form>';
flush();
if (isset($_REQUEST["url"]) && !empty($_REQUEST["url"])) {
$url = $_REQUEST["url"];
$phones = array();
for ($page = 1; $page <= 1; $page++) {
// get page contents
$contents = file_get_contents($url . "&_pgn=" . $page);
echo(htmlentities($contents));
// find all links patterns
// HERE IS THE PROBLEM
$pattern = '/class="lvtitle"><a href="(.*)" class="vip"/';
$linksArray = array();
preg_match_all($pattern, $contents, $linksArray);
print_r($linksArray);
$links = $linksArray[0];
foreach($links as $link) {
$pureLink = str_replace("class=\"lvtitle\"><a href=\"", "", $link);
$pureLink = str_replace("\" class=\"vip\"", "", $pureLink);
// getting sub page contents
$subContents = file_get_contents($pureLink);
// find all links patterns
$subContents = str_replace(" ", "", $subContents);
$phonePattern = '/07[0-9]{9}/';
$phonesArray = array();
preg_match_all($phonePattern, $subContents, $phonesArray);
foreach($phonesArray[0] as $element) {
// check if phone not added previousely to the phones array
if (!in_array($element, $phones)) {
// add it to the phones array
array_push($phones, $element);
echo $element . "<br />";
flush();
}
}
}
}
// print results
foreach($phones as $phone){
echo $phone."<br/>";
}
}
?>
So obviously my question is what am I doing wrong? Why are the matches not being pushed to my $linksArray variable. I really appreciate your help!
This regex works:
"/ class=\"lvtitle\"><a href=\"([^\"]*)\" class=\"vip\"/"
A few issues with your's:
You were trying to capture the URL using (.*), which will match the entire line.
It was not matching the entire line because ebay has two spaces in between the class and href attributes.
Also, as has already been mentioned, you should use the API or DOMDocument for this. But in case you are curious, this is why it wasn't working. I hope that helps!
I have code like this
$word = 'foo';
$char_buff = str_split($word);
foreach ($char_buff as $chars){
echo var_dump($chars);
}
The output was
string(1) "f"
string(1) "o"
string(1) "o"
For some reasons, I want to make the output become only 1 string like this:
string(3) "foo"
I tried with this
$char.=$chars;
echo var_dump($char);
But it shows error Undefined variable: char.
I'm going to assume that you have a good reason for splitting it up, only to put it back together again:
$word = 'foo';
$result = "";
$char_buff = str_split($word);
foreach ($char_buff as $char){
$result .= $char;
}
echo var_dump($result);
Which outputs the following:
string(3) "foo"
str_split() converts a string to an array. There's no need to use this function if you want to keep the whole word.
I would just use implode, much like this:
$string = implode('', $char_buff);
So, why do you split it just to make it a string again?
$word='foo'
$char_buff = str_split($word);
$final = array();
foreach ($char_buff as $chars){
$final[] = $chars;
}
var_dump( implode('', $final) );
Sounds like you are looking for implode()
http://php.net/manual/en/function.implode.php
As for the code you posted
$chars .= $char;
is probably what you were trying to do
Kind of strange to split a string, and then glue it together again, but here goes:
$word='foo'
$char_buff = str_split($word);
// this is what is missing, you have to define a variable first
$newword = "";
foreach ($char_buff as $chars){
$newword .= $chars;
}
echo var_dump($newword);
<?php
$word = 'foo';
$char_buff = str_split($word);
// here is the trick
$length = count($char_buff);
$char_buff[$length] = $word;
foreach ($char_buff as $chars)
{
echo var_dump($chars);
}
?>
Maybe some of you are looking for this answer.
I think var_dump() is no longer necessary for this problem.
<?php
if(isset($_POST['test'])){
$result = '';
for($x=1;$x<=4;$x++){
$ans = $_POST['ans'.$x];
$result .= $ans;
}
echo $result;
}
?>
Here is the HTML
<form role="form" method="post" action="<?php echo $url;?>">
<input type="checkbox" name="ans1" value="A">A
<input type="checkbox" name="ans2" value="B">B
<input type="checkbox" name="ans3" value="C">C
<input type="checkbox" name="ans4" value="D">D
<input type="submit" name="test" value="Submit Answer">
</form>
I am using this piece of code on a site of mine.
If there is PHP code in the array and if you echo it, it does not run.
There is piece of code;
function spin($var){
$words = explode("{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
echo $word." ";
}
}
}
$text = "example.com is {the best forum|a <? include(\"myfile.php\");?>Forum|a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
The file that needs to be included "myfile.php" will not be included. and the PHP codes will be visible. Why is that? How can I solve this problem?
I believe that you will want to run the include statement through eval(). However note that:
"The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand." (PHP.net)
SOURCE: http://php.net/manual/en/function.eval.php
You might try the following:
<?php
function spin($var)
{
$words = explode("\{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
if ( preg_match( "/\<\? include\(\\\"([A-Za-z\.]+)\\\"\)\;\?\>/", $word ) )
{
$file = preg_replace( "/^.*\<\? include\(\\\"([A-Za-z\.]+)\\\"\)\;\?\>.*\$/", "\$1", $word );
$pre = preg_replace( "/^(.*)\<\? include\(\\\"[A-Za-z\.]+\\\"\)\;\?\>.*\$/", "\$1", $word );
$post = preg_replace( "/^.*\<\? include\(\\\"[A-Za-z\.]+\\\"\)\;\?\>(.*)\$/", "\$1", $word );
echo $pre;
include( $file );
echo $post;
}
}
}
}
$text = "example.com is {the best forum|a <? include(\"myfile.php\");?>Forum|a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
?>
My suggestion is a bit of other way,
function spin($var){
$words = explode("{",$var);
foreach ($words as $word)
{
$words = explode("}",$word);
foreach ($words as $word)
{
$words = explode("|",$word);
$word = $words[array_rand($words, 1)];
if(str_replace(" ","",$word) == 'thisparam'){
echo 'a';
include("myfile.php");
echo 'Forum';
}else{
echo $word." ";
}
}
}
}
$text = "example.com is {the best forum| thisparam |a wonderful Forum|a perfect Forum} {123|some other sting}";
spin($text);
where thisparam is you variable $test is the parameter to run the if statement.
I place a str_replace infront of $word to replace strings to get exact word.
Well it is just a string of text after all. The echo will just output the text...
I suggest you look to make use of eval http://php.net/manual/en/function.eval.php
I cant really tell why you wish to do this though. Whenever I need to use eval and friends I stop to think "Should I be doing this?"
Is there any way to tell if a preg_replace was successful or not?
I tried:
<?php
$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/", "/red/");
if ($string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1)) {
echo "<textarea rows='30' cols='100'>$string</textarea>";
}else{
echo "Nope. You didn't have all the required patterns in the array.";
}
?>
and yes, I looked at php docs for this one. Sorry about my stupid questions earlier.
You can use the last param of preg_replace: &$count, which will contain the number of replacements that were done:
$stringz = "Dan likes to eat pears and his favorite color is green and green!";
$patterns = array("/pears/","/green/","/green/");
$new_patterns = array();
foreach ($patterns as $p)
if (array_key_exists($p, $new_patterns))
$new_patterns[$p]++;
else
$new_patterns[$p] = 1;
$string = $stringz;
$success = TRUE;
foreach ($new_patterns as $p => $limit)
{
$string = preg_replace($p, '<b>\\0</b>', $string, $limit, $count);
if (!$count)
{
$success = FALSE;
break;
}
}
if ($success)
echo "<textarea rows='30' cols='100'>$string</textarea>";
else
echo "Nope. You didn't have all the required patterns in the array.";
edited to fix the issue when there are two of the same in $patterns
if (preg_replace($patterns, '<b>$0</b>', $stringz, 1) != $stringz)
echo 'preg_replace was successful'
From the documentation:
If matches are found, the new subject
will be returned, otherwise subject
will be returned unchanged or NULL if
an error occurred.
So:
$string = preg_replace($patterns, '<b>\\0</b>', $stringz, 1);
if($string != $stringz) {
// something was replaced
}
If I have a string that contains a url (for examples sake, we'll call it $url) such as;
$url = "Here is a funny site http://www.tunyurl.com/34934";
How do i remove the URL from the string?
Difficulty is, urls might also show up without the http://, such as ;
$url = "Here is another funny site www.tinyurl.com/55555";
There is no HTML present. How would i start a search if http or www exists, then remove the text/numbers/symbols until the first space?
I re-read the question, here is a function that would work as intended:
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,'http') || (count(explode('.',$u)) > 1)) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
return implode(' ',$U);
}
$url = "Here is another funny site www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);
Edit #2/#3 (I must be bored). Here is a version that verifies there is a TLD within the URL:
function containsTLD($string) {
preg_match(
"/(AC($|\/)|\.AD($|\/)|\.AE($|\/)|\.AERO($|\/)|\.AF($|\/)|\.AG($|\/)|\.AI($|\/)|\.AL($|\/)|\.AM($|\/)|\.AN($|\/)|\.AO($|\/)|\.AQ($|\/)|\.AR($|\/)|\.ARPA($|\/)|\.AS($|\/)|\.ASIA($|\/)|\.AT($|\/)|\.AU($|\/)|\.AW($|\/)|\.AX($|\/)|\.AZ($|\/)|\.BA($|\/)|\.BB($|\/)|\.BD($|\/)|\.BE($|\/)|\.BF($|\/)|\.BG($|\/)|\.BH($|\/)|\.BI($|\/)|\.BIZ($|\/)|\.BJ($|\/)|\.BM($|\/)|\.BN($|\/)|\.BO($|\/)|\.BR($|\/)|\.BS($|\/)|\.BT($|\/)|\.BV($|\/)|\.BW($|\/)|\.BY($|\/)|\.BZ($|\/)|\.CA($|\/)|\.CAT($|\/)|\.CC($|\/)|\.CD($|\/)|\.CF($|\/)|\.CG($|\/)|\.CH($|\/)|\.CI($|\/)|\.CK($|\/)|\.CL($|\/)|\.CM($|\/)|\.CN($|\/)|\.CO($|\/)|\.COM($|\/)|\.COOP($|\/)|\.CR($|\/)|\.CU($|\/)|\.CV($|\/)|\.CX($|\/)|\.CY($|\/)|\.CZ($|\/)|\.DE($|\/)|\.DJ($|\/)|\.DK($|\/)|\.DM($|\/)|\.DO($|\/)|\.DZ($|\/)|\.EC($|\/)|\.EDU($|\/)|\.EE($|\/)|\.EG($|\/)|\.ER($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($|\/)|\.XN--HGBK6AJ7F53BBA($|\/)|\.XN--HLCJ6AYA9ESC7A($|\/)|\.XN--JXALPDLP($|\/)|\.XN--KGBECHTV($|\/)|\.XN--ZCKZAH($|\/)|\.YE($|\/)|\.YT($|\/)|\.YU($|\/)|\.ZA($|\/)|\.ZM($|\/)|\.ZW)/i",
$string,
$M);
$has_tld = (count($M) > 0) ? true : false;
return $has_tld;
}
function cleaner($url) {
$U = explode(' ',$url);
$W =array();
foreach ($U as $k => $u) {
if (stristr($u,".")) { //only preg_match if there is a dot
if (containsTLD($u) === true) {
unset($U[$k]);
return cleaner( implode(' ',$U));
}
}
}
return implode(' ',$U);
}
$url = "Here is another funny site badurl.badone somesite.ca/worse.jpg but this badsite.com www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);
returns:
Cleaned: Here is another funny site badurl.badone but this and and
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', '', $string);
Parsing text for URLs is hard and looking for pre-existing, heavily tested code that already does this for you would be better than writing your own code and missing edge cases. For example, I would take a look at the process in Django's urlize, which wraps URLs in anchors. You could port it over to PHP, and--instead of wrapping URLs in an anchor--just delete them from the text.
thanks mike,
update a bit, it return notice error,
'/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i'
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i', '', $string);
$url = "Here is a funny site http://www.tunyurl.com/34934";
$replace = 'http www .com .org .net';
$with = '';
$clean_url = clean($url,$replace,$with);
echo $clean_url;
function clean($url,$replace,$with) {
$replace = explode(" ",$replace);
$new_string = '';
$check = explode(" ",$url);
foreach($check AS $key => $value) {
foreach($replace AS $key2 => $value2 ) {
if (-1 < strpos( strtolower($value), strtolower($value2) ) ) {
$value = $with;
break;
}
}
$new_string .= " ".$value;
}
return $new_string;
}
You would need to write a regular expression to extract out the urls.