Replace mysql result's one row's spaces into '-' - php

while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo " {$row['id']}. ". "{$row['name']} <br> ".
"Music : {$row['lljhg2']} <br> ".
"Video : {$row['description']} <br> ".
"Song : {$row['artist']} <br> ".
"--------------------------------<br>";}
Some code Like this, I want {$row['name']} in <a href=\"/load/{$row['id']}/{$row['name']}\"> I want this row results all spaces replaced by dash ('-').
If the result is:
Prince Reoy from USA
I want to print this:
prince-reoy-from-usa
Is it possible?

either use this query
select lcase(replace(name, ' ', '-')) from table_name
or this php code
strtolower(' ', '-', str_replace($row['name']))

This will replace spaces with dashes, and make the whole string lower case:
strtolower(str_replace(' ', '-', $row['name']))

You can use implode() which will add the "glue" (the '-') between pieces of the array to make a string. Then you can lower the case of the string all at once with strtolower():
$row_data = strtolower(implode('-', $row));
echo $row_data;

Related

PHP preg_replace commas select option

How can I replace commas with brakes in select option to change from this:
To this:
It seems that my current code doesent work anymore:
// $row[1] = "enum('1','2','3','4','5','6','7','8','9','10')";
$options = explode("', '", preg_replace("/(enum|set)\('(.+?)'\)/", "\\2", $row[1]));
Full code from first image:
$row = $db->query("SHOW COLUMNS FROM namemap LIKE 'multiplier'");
$row = $row->fetch_row();
$options = explode("', '", preg_replace("/(enum|set)\('(.+?)'\)/", "\\2", $row[1]));
print("<tr><td align='left' class='header'>Multiplier:</td>");
print("<td align='left' class='lista' colspan='2'><select name='multiplier'>");
foreach($options as $multiplier) {
$option = "<option ";
if ($multiplier == $results['multiplier'])
$option .= "selected=selected ";
$option .= "value=".$multiplier.">" . unesc($multiplier) . "</option>";
print($option);
}
print("</select></td></tr>");
Here is how I separated the enum string. Not the most elegant thing, but it works:
$options = explode(",",str_replace("'","", str_replace('enum(', '', str_replace(')','', $row[1]))));
Also I got rid of the print() statements. You can output the html directly - separating the html presentation from the php logic helps make the code a little more legible and flexible.
<?php
$row = array("multiplier","enum('1','2','3','4','5','6','7','8','9','10')","YES","","1","");
$options = explode(",",str_replace("'","", str_replace('enum(', '', str_replace(')','', $row[1]))));
?>
<tr><td align='left' class='header'>Multiplier:</td>
<td align='left' class='lista' colspan='2'><select name='multiplier'>
<?php foreach($options as $multiplier) {
$s='';
if ($multiplier == $results['multiplier']) $s="selected";
?>
<option value='<?php echo $multiplier?>' <?php echo $s?>><?php echo $multiplier?></option>
<? } ?>
</select></td></tr>
I think you found the correct place where it is not working any longer:
$options = explode("', '", preg_replace("/(enum|set)\('(.+?)'\)/", "\\2", $row[1]));
The reason is that the split-string "', '" contains a space after the comma while the string returned from preg_replace does not have spaces after the comma.
So using explode with a fixed string does not suffice any longer as entering these values in the database may be with or without space(s) after a comma (and perhaps even before?).
Once seen, the fix could be straight forward. One solution is to use a regular expression pattern as well when "exploding", there is a sister function for that with preg_replace and it is called preg_split:
$options = preg_split("/',\s*'/", ...);
^^^
\s : space character
* : zero or more, as many as possible (greedy)
So exchanging explode with preg_split can upgrade the code to handle cases with zero or more space characters after the comma.
Likewise you could introduce potential space characters also before the comma by allowing them the same, just before the comma.

Count Number Of Words In a Textarea

I have a text area that gets input from a PHP script, and I would like to count the number of words or line breaks in the textarea and echo it below the text area.
This is what the code looks like for the textarea.
<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
<?php $output_array = explode(" ",$output);
$count = count($output_array);
for ($i=0;$i<$count;$i++){
echo $output_array[$i]."\n";
}
?>
</textarea><br />
<br>
<?php
preg_match_all("/(\n)/", $_POST['domains'], $matches);
$total_lines = count($matches[0]) + 1;
echo $total_lines;
?>
<br />
I tried using preg_match_all but the output I get is only "1", regardless of how many line breaks are inside the text area.
$str = 'as aa frd sad as
kjhsdf sdkjh
sd sdkjhsdf
sjkldhfh sdfjh sd';
preg_match_all("/\w+/", $str, $matches);
echo 'Words = ' . count($matches[0]);
echo PHP_EOL;
preg_match_all("/\n/", $str, $matches);
echo 'newlines = ' . count($matches[0]);
echo PHP_EOL;
echo 'So number of line is = ' . count($matches[0])+1;
RESULT
Words = 12
newlines = 3
So number of line is = 4
You can do the following:
$arr = array_filter(explode(" ", $input) function($item) {
return !!$item;
});
$count = count($arr) + count(explode("\n", implode(",", $arr)));
This splits the string by space, filters out empty items to avoid issues due to multiple spaces found between words, then glues the array back into a string, splits it by newline and adds the two counts together.

Explode() String Breaking Array Into Too Many Elements

I am working on scraping and then parsing an HTML string to get the two URL parameters inside the href. After scraping the element I need, $description, the full string ready for parsing is:
<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>
Below I use the explode parameter to split the $description variable string based on the = delimiter. I then further explode based on the double quote delimiter.
Problem I need to solve: I want to only print the numbers for MeetingID parameter before the double quote, "773".
<?php
echo "Description is: " . htmlentities($description); // prints the string referenced above
$htarray = explode('=', $description); // explode the $description string which includes the link. ... then, find out where the MeetingID is located
echo $htarray[4] . "<br>"; // this will print the string which includes the meeting ID: "773">Description</a><br>"
$meetingID = $htarray[4];
echo "Meeting ID is " . substr($meetingID,0,3);
?>
The above echo statement using substr works to print the meeting ID, 773.
However, I want to make this bulletproof in the event MeetingID parameter exceeds 999, then we would need 4 characters. So that's why I want to delimit it by the double quotes, so it prints all numbers before the double quotes.
I try below to isolate all of the amount before the double quotes... but it isn't seeming to work correctly yet.
<?php
$htarray = explode('"', $meetingID); // split the $meetingID string based on the " delimiter
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
?>
Question, why is the array $meetingID[0] not printing the THREE numbers before the delimiter, ", but rather just printing a single number? If the explode function works properly, shouldn't it be splitting the string referenced above based on the double quotes, into just two elements? The string is
"773">Description</a><br>"
So I can't understand why when echoing after the explode with double quote delimiter, it's only printing one number at a time..
The reason you're getting the wrong response is because you're using the wrong variable.
$htarray = explode('"', $meetingID);
echo "Meeting ID0 is " . $meetingID[0] ; // this prints just the first number, 7
echo "Meeting ID1 is " . $meetingID[1] ; // this prints just the second number, 7
echo "Meeting ID2 is " . $meetingID[2] ; // this prints just the third number, 3
echo "Meeting ID is " . $htarray[0] ; // this prints 773
There's an easier way to do this though, using regular expressions:
$description = '<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>';
$meetingID = "Not found";
if (preg_match('/MeetingID=([0-9]+)/', $description, $matches)) {
$meetingID = $matches[1];
}
echo "Meeting ID is " . $meetingID;
// this prints 773 or Not found if $description does not contain a (numeric) MeetingID value
There is a very easy way to do it:
Your Str:
$str ='<a target="_blank" href="CoverSheet.aspx?ItemID=18833&MeetingID=773">Description</a><br>';
Make substr:
$params = substr( $str, strpos( $str, 'ItemID'), strpos( $str, '">') - strpos( $str, 'ItemID') );
You will get substr like this :
ItemID=18833&MeetingID=773
Now do whatever you want to do!

PHP remove tab(\t) tacks on random numbers

I appear to be having a problem with string replace
$vals= "1/5/2012 $4,510.64
"; //simulating web entry that would be copied and pasted from excel.
$vals = str_replace(array("\t"), " ", $vals);
echo $vals;
1/5/2012 $4,510.64 13257216001415138792
same for trim
$vals= "1/5/2012 $4,510.64
";
$vals=trim(preg_replace('/\t+/', ' ', $vals));
echo $vals;
1/5/2012 $4,510.641325721600
But if I tell it not to replace tabs with spaces, but instead delete them, THEN it doesnt add on any junk.
$vals= "1/5/2012 $4,510.64
";
$vals=trim(preg_replace('/\t+/', '', $vals));
echo $vals;
1/5/2012$4,510.64
A little help? I would love for tabs to get replaced with spaces without random numbers being tacked on at the end. Thanks

How to explode a string, with spaces and new lines?

I would like to explode a string (separated based on a delimiter and placed into an array), using both a space (" ") and a newline ("\n") as a delimiter.
The method (which I don't think is the best way) is to:
Explode the array by spaces
Remake the string from the array
Explode it again for new lines
MySQL escape the individual elements.
Question: How do I exploded a string by both a space and new line?
Reference to: new line Array
You could just do a
$segments = preg_split('/[\s]+/', $string);
This function will split $string at every whitespace (\s) occurrence, including spaces, tabs and newlines. Multiple sequential white spaces will count as one (e.g. "hello, \n\t \n\nworld!" will be split in hello, and world! only, without empty strings in the middle.
See function reference here.
You can use preg_split to explode the content using multiple delimiter
$pattern = '/[ \n]/';
$string = "something here ; and there, oh,that's all!";
echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
Always go from the bigger to the smaller one.
So first split by "\n" and then split by " ".
$data = "This is a test\nAnd something new happens.";
$rows = explode("\n", $data);
$words = array();
foreach($rows as $row) {
$temp = explode(" ", $row);
foreach($temp as $word)
$words[] = $word;
}
Will give you an array with all words in it.
You can use to explode the content using multiple delimiter.
Sample code
<?php
$str = "Brand : Pandora~ Collection : Summer 13~ Colour : Multi~ Gender : Ladies~ Material : Murano Glass~ Our Code : 0573835~ Packaging : Pandora Branded Packaging~ Product Code : 750513~ Product Type : Bead~ Style : Contemporary";
$r1 = explode("~", $str);
$stringtxt = '<table>';
if (count($r1) > 0) {
foreach ($r1 as $value) {
$rows = explode(":", $value);
$stringtxt .= '<tr>';
$stringtxt .= '<td>' . $rows[0] . '</td><td>' . $rows[1] . '</td>';
$stringtxt .= '</tr>';
}
}
$stringtxt .= '</table>';
print $stringtxt;
?>
Output
<table>
<tr><td>Brand </td><td> Pandora</td></tr>
<tr><td> Collection </td><td> Summer 13</td></tr>
<tr><td> Colour </td><td> Multi</td></tr>
<tr><td> Gender </td><td> Ladies</td></tr>
<tr><td> Material </td><td> Murano Glass</td></tr>
<tr><td> Our Code </td><td> 0573835</td></tr>
<tr><td> Packaging </td><td> Pandora Branded Packaging</td></tr>
<tr><td> Product Code </td><td> 750513</td></tr>
<tr><td> Product Type </td><td> Bead</td></tr>
<tr><td> Style </td><td> Contemporary</td></tr>
</table>

Categories