select category after link remove special characters? - php

I have a page to show some people's name, so user can click and see their related posts.
The problem is people with ' or . in the name or any other special character.
To create the URL I need to remove this characters:
Marie E.A
Josh O'Reilly
php to create the link:
$categorialink = strtolower($categoria);
$categorialink = str_replace(' ', '_', $categorialink);
$categorialink = preg_replace('/[^A-Za-z0-9\_-]/', '', $categorialink);
will become:
www.mypage.com/person/marie_ea
www.mypage.com/person/josh_oreilly
the problem is to get this values from mysql, Mysql record the name as it is (Marie E.A) and I can't go back to the original person's name.
mysql LIKE could help, but can open another person page by select something similar eg: Marie E.B instead of Marie E.A.
$categoryp = $_GET['categoria'];
$category = str_replace("_", " ", $categoryp);
SELECT id, categoria FROM categoria where categoria = 'marie ea' limit 1 //$category value - return nothing
how to solve this?

Just use urlencode () . That will translate string by only replacing letters, not deleting them. Later if You need to get previous name, just use rawurldecode() .

Related

escape spaces in id attributes or deleting them in php section

i get different string (like a, b, hospital, schools, jobs to work etc. ) as $divname from my db in my PHP section. i use this values as id in mydiv elemnents.
<div id="'.$divname.'"></div>
there is no problem for $divname = a, b, hospital or school but when it comes to jobs to work there is a huge problem cause my id gets spaces and it returns an error to me.
<div id="jobs to work"></div> //as evryone state spaces in id variable is an error.
now my question i need use this $divame variables in my id attribute. how can i do this? how can i delete those spaces or any more idea for using those in id attributes are welcome.
You may do two things:
Use a hashing function to create new id, which will be unqiue as long as your ids are unique as:
$newdivid = md5($olddivid);
You may write a function to remove spaces and combine such string items
function remove_spaces($str) {
$str_arr = explode(' ', $str);
$newstr = "";
foreach($str_arr as $sitem){
$newstr .= trim($sitem);
}
return $newstr;
}
Hope this solves your problem.
i found a php command in another Sof question for this purpose
$new_divname = str_replace(' ', '', $divname);
it deletes all spaces.. and of course my question gets a dublicate:

Trim extra space from column Mysql

I have a old database in which column categories is stored in bad shape ... with extra space in them, example
Hotels in London
Hotels in Manchester
is there a way i can alter this space inside the table ... if i can remove extra space from categories (middle space) to get output like this
Hotels in London
Thx
You can use the REPLACE function like
update table set columnName= REPLACE(columnName,' ',' ')
Pull the data down into values that you can do work on then remove the extra white space using:
$foo = trim(preg_replace( '/\s+/', ' ', $foo ));
then write it back to the DB.
I had the similar situation where i had to remove the extra spaces while searching value for a particular field.
I have used replace function of mysql, like this
SELECT * FROM `tableName` WHERE post_id = 'xxx' AND replace(`fieldName`,' ','') Like '%JobOppurtunity%' ;
Here what replace does, it recursively removes all the spaces in the fieldName and concatenates the field value and then searches my concatenated string after LIKE keyword.
So if I had field value 'Job Oppurtunity', it will convert it into 'JobOppurtunity' and obviously I would have already concatenated my search string by any string function or regular expression. Like it did this way
$txt_search_qry = trim(preg_replace( '/\s+/', '', $txt_search_qry));
Another quick and simple method I found is this:
REPLACE(REPLACE(REPLACE(columnName,' ',' !'),'! ',''),' !',' ')

Remove values in comma separated list from database

I have a table in my MySQL database called 'children'. In that table is a row called 'wishes' (a comma separated list of the child's wishlist items). I need to be able to update that list so that it only removes one value. i.e. the list = Size 12 regular jeans, Surfboard, Red Sox Baseball Cap; I want to remove Surfboard.
My query right now looks like this
$select = mysql_query('SELECT * FROM children WHERE caseNumber="'.$caseNum.'" LIMIT 1 ');
$row = mysql_fetch_array($select);
foreach ($wish as $w) {
$allWishes = $row['wishes'];
$newWishes = str_replace($w, '', $allWishes);
$update = mysql_query("UPDATE children SET wishes='$newWishes' WHERE caseNum='".$caseNum."'");
}
But the UPDATE query isn't removing anything. How can I do what I need?
Using these user-defined REGEXP_REPLACE() functions, you may be able to replace it with an empty string:
UPDATE children SET wishes = REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '') WHERE caseNum='whatever';
Unfortunately, you cannot just use plain old REPLACE() because you don't know where in the string 'Surfboard' appears. In fact, the regex above would probably need additional tweaking if 'Surfboard' occurs at the beginning or end.
Perhaps you could trim off leading and trailing commas left over like this:
UPDATE children SET wishes = TRIM(BOTH ',' FROM REGEXP_REPLACE(wishes, '(,(\s)?)?Surfboard', '')) WHERE caseNum='whatever';
So what's going on here? The regex removes 'Surfboard' plus an optional comma & space before it. Then the surrounding TRIM() function eliminates a possible leading comma in case 'Surfboard' occurred at the beginning of the string. That could probably be handled by the regex as well, but frankly, I'm too tired to puzzle it out.
Note, I've never used these myself and cannot vouch for their effectiveness or robustness, but it is a place to start. And, as others are mentioning in the comments, you really should have these in a normalized wishlist table, rather than as a comma-separated string.
Update
Thinking about this more, I'm more partial to just forcing the use of built-in REPLACE() and then cleaning out the extra comma where you may get two commas in a row. This is looking for two commas side by side, as though there had been no spaces separating your original list items. If the items had been separated by commas and spaces, change ',,' to ', ,' in the outer REPLACE() call.
UPDATE children SET wishes = TRIM(BOTH ',' FROM REPLACE(REPLACE(wishes, 'Surfboard', ''), ',,', ',')) WHERE caseNum='whatever';
Not exactly a direct answer to your question, but like Daren says it's be better having wishes as its own table. Maybe you could change your database schema so you have 3 tables, for instance:
children
-> caseNum
-> childName
wishes
-> caseNum
-> wishId
-> wishName
childrensWishes
-> caseNum
-> wishId
Then to add or delete a wish for a child, you just add or delete the relevant row from childrensWishes. Your current design makes it difficult to manipulate (as you're finding), plus leaves you at risk for inconsistent data.
As a more direct answer, you could fix your current way by getting the list of wishes, explode() 'ing them, removing the one you don't want from the array and implode() 'ing it back to a string to update the database.
Make wishes table have this format:
caseNumber,wish
Then you get all of a child's wishes like this:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ?
Removing a wish becomes:
DELETE from wishes where caseNumber = ?
Adding a wish becomes:
INSERT into wishes (caseNumber,wish) values (?,?)
Returning one wish becomes:
SELECT * FROM children c left join wishes w on c.caseNumber = w.caseNumber WHERE c.caseNumber= ? LIMIT 1
Having the wishes indexed in an array which is thereafter serialized could be an idea, otherwise you would need to retrieve the string, slice it, remove the part you don't want, then concatenate the remains. This can be done by using the explode() function.
If you were to use an array, you would retrieve the array and then sort through it with a loop like this:
// Wishes array:
// Array (
// [0] Regular Jeans
// [1] Surfboard
// [2] Red Sox Baseball Cap
// )
$wishes = $row['wishes']; // This is a serialized array taken from the database
$wishes = unserialize($wishes);
foreach ($wishes as $key => $value) {
if ($value == 'Surfboard') {
unset($wishes[$key]);
break;
}
}
$wishes = serialize($wishes);
// Update database
Keep in mind that index [1] now won't exist in the array, so if you wish to have a clean array you should loop through the array and make it create a new array by itself:
foreach ($wishes as $wishes) {
$newArray[] = $wishes;
}
I think the best answer to such issue is here
The best way to remove value from SET field?
query should be like this which covers the ,value or value, or only value in the comma separated column
UPDATE yourtable
SET
categories =
TRIM(BOTH ',' FROM
REPLACE(
REPLACE(CONCAT(',',REPLACE(col, ',', ',,'), ','),',2,', ''), ',,', ',')
)
WHERE
FIND_IN_SET('2', categories)
Here you can have your condition in where clause. for more details refer above link.
You can create function like this:
CREATE FUNCTION `remove_from_set`(v int,lst longtext) RETURNS longtext CHARSET utf8
BEGIN
set #lst=REPLACE(#lst, ',,', ',');
set #lng=LENGTH(#lst) - LENGTH(REPLACE(#lst, ',', ''))+1;
set #p=find_in_set(#v,#lst);
set #l=SUBSTRING_INDEX( #lst, ',', #p-1);
set #r=SUBSTRING_INDEX( #lst, ',', #p-#lng);
IF #l!='' AND #r!='' THEN
return CONCAT(#l,',',#r);
ELSE
RETURN CONCAT(#l,'',#r);
END IF;
END
Using:
SELECT remove_from_set('1,,2,3,4,5,6',1)

php: how can i change Stored value into user friendly values !

the problem in short,
Field:ProfileItems = "action,Search,Work,Flow,pictures";
Mysql query = "SELECT ProfileItems FROM addUsers";
then I explode with , making array e.g.: array('action','search',...etc)
and create fields for ,
Result:
<form>
action : <input type=text name=action>
search : <input type=text name=search>
...etc
<input type=submit>
</form>
My problem is how can I replace names in the database with more user friendly ones (add description) to fields without using an IF statement??
//created asoc array with Key = search item and value = user friendly value
$prase = array("ABS" => "ABS (Anti lock braking System)"
,"DriverAirBag" => "Air bags");
$string= "ABS,DriverAirbag,GOGO,abs";
foreach($prase as $db=>$eu){
echo "if $db will be $eu<br>";
echo str_ireplace($eu,$db,$string);
}
echo $string;
Tried above but was an epic fail :D !.. can you please help me out ?
Having a map inside PHP is not an unreasonable approach, but you're doing the str_ireplace() backwards: it's search, replace, subject, so in your case str_ireplace($db, $eu, $string);
But just doing a str_ireplace() on a comma-separated list of strings is not ideal anyway. For one thing, imagine if after you did the substitution for ABS you then encountered another profile item that matched lock (which just so happens to appear in "Anti-lock braking system"). Oops. Now you've overwritten your earlier replacement!
How about something like this:
$prase = array("ABS" => "ABS (Anti lock braking System)"
,"DriverAirBag" => "Air bags");
$string= "ABS,DriverAirbag,GOGO,abs";
$fields = explode(',', $string);
foreach($fields as $field) {
$friendly = $field;
if (isset($phrase[$field]))
$friendly = $phrase[$field];
echo htmlspecialchars($friendly) . ': <input type="text" name="' . htmlspecialchars($field) . '" />
}
The key here is that you're handling each field separately. And you're never just doing a replacement; you're looking specifically for the keywords "ABS" or "DriverAirbag". If there's not an exact match, you don't have a human-friendly name for that item, and there's no point doing any replacement.
All this can be improved even further if you have the ability to change the database schema. Storing a comma-separated list is never desirable. You should have a table with a schema something like:
field_id (e.g., "ABS")
name (e.g., "Anti-lock Braking System")
And another table like:
user_id (I'm inferring a little here from the name addUsers — whatever field/s you have in addUser now identifying the person)
field_id (i.e., foreign key to the above field table)
Note that you may end up with many rows in this table for each person (1, 'ABS'), (1, 'DriverAirbag')
But then your query can become
SELECT field, name
FROM user_field
INNER JOIN field USING (field_id)
Now you get back one row for each field (no explode required!) and each row includes both the computer-friendly and human-friendly name.

Split multiple lines and input them in separate row in a database

I am trying to create a php script that inputs the HTTP links pasted into a textarea into a separated row in a database. More exactly:
First page is where the textarea (name=textarea-linkfield) is, links are going to be pasted here
http://www.stackoverflow.com
http://www.yahoo.com
....
http://google.com
The links are being carried over into the php script with $linkfield=$_POST['textarea-linkfield']; and I would like the links to be inserted into the database, each http link per row. Database name: site, table name plow, columns: id, url, ...
L.E. I tried just as proof of concept:
$linkfield=$_POST['textarea-linkfield'];
$strip=explode("\n",$linkfield);
echo $strip[1];
but I get 500 INTERNAL SERVER ERROR
L.E.2
The answer:
// Split the string into pieces
$pieces = explode("\n", str_replace(array("\n", "\r\n"), "\n", trim($linkfield)));
// Build the top of the INSERT query
$sql = "INSERT INTO `plow`(`url`) VALUES\n";
// Build the rest of the ;INSERT query by re-assembling the
// pieces.
$sql .= "('";
$sql .= implode("'), ('", $pieces);
$sql .= "')";
mysql_query($sql) or die ('Error: ' . mysql_error());
mysql_close();
Thanks to all for their help.
Chris.
Depending on your os a newline can be "\n", "\r\n" or "\r".
Give this a shot:
$strip=explode("<br>", nl2br($linkfield));
or maybe safer:
$strip=explode("\n", str_replace(array("\n", "\r\n"), "\n", $linkfield));
use preg_match to find each URL and add it to the database.
Example 3 on this page should do the trick: http://php.net/manual/en/function.preg-match.php
this way you can enter URLs without having to use a new line.
if you're only using URLs, then you could also add a delimeter after each URL i.e. a comma (which isnt used in a URL) to explode them with using the explode() idea in the comment.
Here is your question, answered:
http://bytes.com/topic/php/answers/850719-extracting-individual-lines-multiline-text-box-processing

Categories