PHP - Complicated String Replace
Hi Guys
I'm sure this is really simple for you experts but it's proving to be my nemesis! I have an array of words: eg. $words = array('Apples','Bananas','Cherries'); and would like to search a string of text for these words and create link tags around them based on a simple template, <a href="#">$word_found</a> $text = "I love eating apples and bananas but hate cherries!"; So i would like to return a string like this: $text = "I love eating <a href=#>apples</a> and <a href="#">bananas</a> but hate <a href="#">cherries!</a>"; Now, I need it to do a case insensitive search, but just wrap tags around the words it finds, leaving the case as it was found in the string. I want to avoid using a function where I have to list all the replacements like this: function replace_text($text){ $replace = array('apples' => '<a href="#">apples</a>','bananas' => '<a href="#">bananas</a>'); $text = str_ireplace(array_keys($replace), $replace, $text); return $text; } because it seems very messy and long winded. Also it's not case insensitive. It seems like there must be a way of simply searching for the words in my array and wrapping tags around the found words. Please can anyone help!? Many Thanks Dan Similar TutorialsThe situation is that I have a large string with some identifiers to say "replace me" with something else. My goal is to replace the values, but if one replacement includes one of the other keys, I don't want to replace it.
For example:
<?php $str = 'some blob ~abc~ followed by ~def~'; $arr_orig = array( '~abc~', '~def~' ); $arr_new = array( 'value~def~', 'blah' ); echo str_replace( $arr_orig, $arr_new, $str ); ?>This will echo: some blob valueblah followed by blah But that's not what I'm trying to accomplish. Basically, I want ~abc~ to be replaced with the literal: value~def~ and for the ~def~ that happens to be part of that string to NOT be replaced. I hope what I'm asking is clear. Basically, preg_replace/str_replace with arrays seems no different than just doing a FOR loop and replacing ~abc~ and then ~def~. But that's not what I need. I'm hoping that if ~abc~ is replaced with text that happens to be another identifier -- ~def~, ~xyz~, whatever -- that this already replaced text is not again replaced. Is there a built-in function to do something like this? If not, should I just parse the whole string and count characters or something? Seems like a pain (and slow!) For this example, $row2['author'] = "1" $user = 'user'.$row2['author']; if (!isset($$user)){ $result = $connector->query('SELECT * FROM users WHERE ID = '.$row2['author']); $$user = $connector->fetchArray($result); } echo '<a href="user.php?user='.($$user['ID']).'">'.$$user.'</a></p>'; The problem is it is a weird variable that also has an array, but when i use echo $$user['ID']; It errors out saying Notice: Quote Undefined variable: u So I am wondering how to word it to set the variable up properly, and how to call items in the array. Thanks in advance Hi - newbie to php - I need to search a string and possibly replace part of it. This is how I would do it in perl: Code: [Select] if ($homepage) { if ($homepage !~ /http/i) { $homepage = "http:\/\/" . $homepage; } } I have a homepage field in the database but sometimes people put the http in, and sometimes they leave it out. In perl I can figure it out and format accordingly but it doesn't work in PHP. I'm not sure if the first line even works in PHP. Maybe if to say something like: if $homepage is not equal to nothing. I'm not sure. Any help would be appreciated. Thanks. hello again need some advice cant get it working Code: [Select] SELECT * FROM `tsue_members` WHERE memberid=0 if ($row['memberid'] == '0') { $img = "1.gif"; } echo $img; How can I replace the comma from a string like this: You, like this => You like this You, Derp, like this => You and Derp like this You, Derp, Derpina, like this => You, Derp and Derpina like this You, Derp, Derpina, Derpson, like this => You, Derp, Derpina and Derpison like this Hello All, I've been knocking my head against the wall for several hours trying to figure out what's going on with a simple string replace. For the most part it is working beautifully, but if a string contains a similar but not exact match it still replaces the non match. I was under the impression that str_replace always looks for an exact match. I have custom tags that are in strings of text that are structured like: [A_CUSTOM_HEADER] [A_CUSTOM_TITLE] and so on. They always start with "[A_CUSTOM" and end with a " ] ". In between the start and end can be just about anything. So my problem is if I have [A_CUSTOM] and [A_CUSTOM_TAG] in the same text str_replace seems to incorrectly replace all the [A_CUSTOM_TAG] with the [A_CUSTOM] content and the match never happens for the [A_CUSTOM_TAG] content. For example: $content = 'Here is some text and [A_CUSTOM]. Here is more text and [A_CUSTOM_TAG]'. $content = str_replace('[A_CUSTOM]','I have a and custom',$content); $content = str_replace('[A_CUSTOM_TAG]','I have a, custom and tag',$content);So running that code The [A_CUSTOM_TAG] content never gets replaced correctly, it is replaced on the first pass with the [A_CUSTOM] replacement content. I hope this make sense I'm trying to explain it the best I can. I tried using preg_replace() with \b to match the whole word but didn't get anything close to the respected results...haha I'm sure I'm missing something simple...or at least I hope I am. Thanks in advance! Edited by Twitch, 22 May 2014 - 11:52 AM. May I please ask one more question? About replacing a string only if it appears *after* a particular string?
I'm having trouble replacing all occurrences of "wheel" with "TIRE" but only when the word "wheel" is after this: (W/
Example:
From this:
A large wheel is shiny.
Big 4 wheel truck (W/ wheel)
Car with a wheel, and a small toy (w/ wheel)
Four wheelers are cool
To this:
A large wheel is shiny.
Big 4 wheel truck (W/ TIRE)
Car with a wheel, and a small toy (w/ TIRE)
Four wheelers are cool
Unfortunately, I thought this worked:
$fixed = str_ireplace('wheel','tire',substr($original_string,stripos($original_string,'(W')));
...until I realized it was *cutting off* all characters up until that first '(W/'
What can be done to make this work?
Edited by Nyla, 20 November 2014 - 09:40 PM. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=319445.0 Hi, I am trying to take a string from a database and replace everything within {} with code... similar to how posting in a forum works. so say I have "...Lorem ipsom {gallery:1} sit imet..." it will take that string (from a DB) and replace "{gallery:1}" with "<?php gallery('1'); ?>". How can this be done? Or is there keywords I can search on to find the answer? Thank you in advance. hey guys just a simple one...im trying to replace {$name} but i dont think ive got the right prefix in the str_replace function...if anyone could tell me where i am going wrong please $content = str_replace("{/$".$variable."}", $value, $content); {$name} I wanted to replace a strings in a large text file .. what would be the fastest way ?! e.g the text file contains .. INSERT INTO `subjects` VALUES (1, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (2, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (3, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (4, 'some text here', 'some text here', 'some text here'); INSERT INTO `subjects` VALUES (5, 'some text here', 'some text here', 'some text here'); I wanted to replace the string " VALUES (1, " with "VALUES (" in each line .. I'm new in PHP so any response would be much appreciated .. thanks I embed videos on my site. I submit the embed codes to my database using a form. The codes look like this:
<iframe width="560" height="315" src="//www.youtube.com/embed/xDIgbjDGsOM?rel=0" frameborder="0" allowfullscreen></iframe>Before I submit each code, I have to change its width and height, and I have to add this: &showinfo=0after this: ?rel=0Is there a function that will allow me to do all of that simultaneously? I know about str_ireplace(). It will let me replace ?rel=0 with ?rel=0&showinfo=0, but I don't know how to simultaneously make the other changes. It's not helping that the embed code includes quotation marks. Hey I have a string that looks like the following: Quote top-php-tutorials-2.html I have a script that cycles through each page. The 2 in the quote above is the page number. How can I extract the number between the - and the .html and replace it with another number? I've tried Code: [Select] substr($engine->selectedcaturl, 0,-6).$v.".html"But then I realised this only works for numbers that are 1 digit long Any input would be appreciated Hi i wrote a find and replace code but my code replace last value of array and skip the first, second.... values in the array. Please give me an idea because i stack with this code. Regards $KeyWord = explode("\n", $RowGetWords['KEYWORDS']); $Replace = explode("\n", $RowGetWords['ReplaceTo']); for($i=0; $i<count($KeyWord); $i++){ $pattern = $KeyWord[$i]; $replace = "<a href=\"" .$URL. "\" target=\"_blank\" >" .$Replace[$i]. "</a>"; $html = str_replace($pattern, $replace, $Row['MessageBody']); } <?php echo $myname; $myname = "Bradery"; ?> That does not work.. is there any way to get it to work without doing this <?php $myname = "Bradery"; echo $myname; ?> Quote Parse error: syntax error, unexpected '"', expecting ']' in /homepages/27/d193007783/htdocs/maddogmania/new_application/roster.php on line 41 $text=''; for($i=1; $i<=$roster_max; $i++){ $text .= " LINE41 `player" . $i . "_number` = '$_POST[player" . $i ."_number]' , `player" . $i . "_name` = '$_POST[player" . $i ."_name]' , `player" . $i . "_grade` = '$_POST[player" . $i ."_grade]' , `player" . $i . "_phone` = '$_POST[player" . $i ."_phone]' , `player" . $i . "_email` = '$_POST[player" . $i ."_email]' , `player" . $i . "_parents` = '$_POST[player" . $i ."_parents]' , "; } Thanks for the help! I have inherited this database and can't change the design. I need to perform a SELECT query and group certain records together for matching employeeID values. The fields: employeeID field1 field2 date (1) field1 can be 1,2,3,4 or 5 only (2) field2 can be a,b,c or a number from 1-100 (varchar though) (3) if field1 and field2 are blank/empty then group together So: employeeID / field1 / field2 / date 32 / 3 / / 1297184426 45 / / b / 1248723499 32 / 3 / / 1258762988 20 / / / 20 / / / 1268722384 So record 1 and 3 above will be grouped, and so will 4 and 5. When I mean grouped, I mean so that only one record will be returned / displayed. Also, when it displays only one record due to being 'grouped', I would like it to return the highest 'date' field value (UNIX Timestamp value) (so the newest / latst date) OR if one of the records is empty then show this instead. So in the above example, record 1 & 3 will return a date of 1297184426 and records 4 and 5 will return nothing for date. Ok i have been after the solution for this for a while and I have finally got it in a state where it is producing results but....... they are wrong so I will start from the beginning with what I have and what I am trying to do. I have these tables Members Id Name Clubs ID Name Permission ID Name Link MemberID PermissionID ClubID When a member joins a club thier ID ant the ID of the club are entered into the link table along with their permission (as a number) so MemberID PermissionID ClubID 01 02 01 I have a loop which is going to echo the clubs a member is a part of. So for my querys function GetUser($user) { $qFindUser = "SELECT * FROM members WHERE email = '$user'"; $rFindUser = mysql_query($qFindUser); $UserInfo = mysql_fetch_array($rFindUser); return $UserInfo; } function GetLinkByMemberID($link) { $qLink = mysql_query("SELECT * FROM link WHERE memberID = '$link'"); $Link = mysql_fetch_array($qLink); return $Link; } function GetClub1($clubs) { $qFindClub = mysql_query("SELECT * FROM clubs WHERE clubID = '$clubs'"); return $qFindClub; } function GetPermission($per) { $qPermission = mysql_query("SELECT * FROM `permissions` WHERE permissionID = '$per'"); $permission = mysql_fetch_array($qPermission); return $permission; } $User = GetUser($_SESSION['Username']); // returns as array from the login details all member details $Link = GetLinkByMemberID($User['memberID']); // returns as a fetch array all clubs the member is a part of $Club = GetClub1($Link['clubID']); // returns as the query $permission = GetPermission($Link['permission']); //returns as array so I can echo the permission word not ID Now the loop is limited by 3 so <?php $Club = mysql_fetch_array($Club); $stack3 = ($Club+$Link); for($i = 0; ($CP = ($stack3)) && $i < 3; $i++ ){ ?> <tr> <th scope="col"><img name="" src="" width="32" height="32" alt="" /></th> <th scope="col"><?php echo $CP['name']; //from the club table ?><span class="ownertext"> <?php echo $CP['permission']; //from the link table ?> The problem I'm having the the loop is returning the first record its selects 3 times and not echoing each club once. I have worked on it for so long I can no longer make sense of it. Can anyone see my errors and point out just how to fix it? Im guessing it involves something to do with how Im finding my permission but I really dont know. As im sure you can see from the code Im a php beginner so Im struggling to make sense of this. I want to get the most recent 15 instances of my a_players_review table THEN sort them by grade, then last name. Ordering the r.id first just gives me a list of rows that I can't do much else with, unless I'm missing how I can code the output. Below is what I had. ORDER BY looked good until I started filling in more rows and seeing kids in grade = 2021 pushing more recent rows off the list. Nested ORDER BY seems frowned upon, and I'm not even sure they work. I kept getting parameters errors. I really can't make heads or tails of nested SELECTs. That might be the answer, but I've been unable to take what I've seen and apply it without getting a parameters error.
$query = "SELECT *,p.id,b.playerID,b.id,s.toggle AS stoggle,o.toggle AS otoggle,p.city,p.school,s.city,s.school,r.opp_city,r.opp_school,o.city,o.school,r.city,r.school FROM a_players_reviews r LEFT JOIN a_players p ON CONCAT (r.nameFirst,r.nameLast) = CONCAT (p.nameFirst,p.nameLast) LEFT JOIN a_schools s ON CONCAT(r.city,r.school) = CONCAT(s.city,s.school) LEFT JOIN a_schools o ON CONCAT(r.opp_city,r.opp_school) = CONCAT(o.city,o.school) LEFT JOIN a_player_bookmark b ON p.id = b.playerID && '". $userID ."' = b.userID WHERE p.id = b.playerID && '". $userID ."' = b.userID && bookmark>0 ORDER BY p.grade,p.nameLast,r.id desc LIMIT 15 "; Edited April 7, 2020 by Jim R I have a list of id's between 1 - 8 which represents a print size that I need to use to calculate shipping costs, but the calculation that I need to perform is complicated. I will try to explain to the best of my abilities. I also need to query a database table to make sure the shipping rates are always up-to-date id's <= 4 will ship for $4.95 now matter how many id's are listed. Eg: 1,2,3,4,3,2,4,2,4 will ship for a total of $4.95 will query price db as 1 id's <= 5 will ship for $6.00 now mater how many id's are listed. Eg: 1,3,3,1,2,3,5,5,5,4,3,3 will ship for a total of $6 will query price db as 2 id's <= 6 will ship for $8.00 now mater how many id's are listed. Eg: 1,3,6,1,6,3,5,5,5,4,3,3 will ship for a total of $8.00 will query price db as 3 id 7 will ship for $5 * Quanity + any of the examples above will query price db as 4 id 8 will ship for $15 * Quantity + any of the examples above will query price db as 5 table structure for shiprates is id, price |