Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Better Method For Search And Replace In String


Here is an example of the type of string I am trying to search and replace,

Generic text about *2nothing~ in particular. Just need to *5extract certain~ characters out of the text.

I need to search the string for "*", collect the number directly after the "*", then extract the text, and watch for the "~" character to denote the end of the text.

Then the information is sent to a new function i.e. new("2", "nothing")

The new function formats the data and returns it into the original string.

Currently I am just looping through the string and replacing as I go, but I imagine their is a better and more efficient way.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Search And Replace In String
Im using the following to search for charictors in a string that are causing problems, and placing a infrount of them.  Im trying to do it using:

<?php
$str = "string's";
$invalied_chars = array(" ", "'");
$result = str_replace($invalied_chars, "", $str);
echo $result;
?>

The bit im confused by was how to keep the old charictor, just proceeding it with a rather then replacing it?

How To Replace An Item In The Url Search String
Using PHP 4, what is the most elegant way to replace a parameter
value in a url query string? I want to replace the "Order" parameter,
but it could occur anywhere in the query string.

myfile.php?Param1=Hi+there&Order=ColumnA&Param3=Bye+Bye
myfile.php?Order=ColumnA
myfile.php?Param1=Anotehr+example&Order=ColumnA

after applying this function, I'd like the result of the above examples
to be

myfile.php?Param1=Hi+there&Order=ColumnB&Param3=Bye+Bye
myfile.php?Order=ColumnB
myfile.php?Param1=Anotehr+example&Order=ColumnB

Partially Replace A String With Data From The Same String...
I'm trying to write a script to help import some old HTML files as blog post for my website, these HTML files are 300-2000 lines long. I am currently using fgets() to read the files one line at a time, clean them and write them to the database in the appropriate format once the entire article is completed.

My issue is many of the links included on these post no longer exist (some date into the '90s) and I want as part of my importing function to "fix" these links as so. Code:

Search And Replace
im developing a script which basically searches and replaces strings on
remote sites and spews them out on the local server, im having a problem or
two with making images come out right, i dont want to download the images to
the local server, i simply want them to grab them from the remote server

in addition, i want all links to link through the script that is grabbing
the site, heres the code so far: Code:

Search And Replace?
does php have a function where it can search a database record and replace it with something else? example. say i have a record in a database and in that record theres a www.domain.com and i want php to search that record and replace that www.domain.com with <a href='www.domain.com'>www.domain.com</a> make any sense?

Search Replace
I'm trying to find some help to be able to search through a given string and change any occurence of &qoute ONLY between < > brackets... and keep the whatever else is in between those brackets the same. $string = "Hi i'm dumb &qoute < &qoute >" Only the one in brackets should be changed.

Search And Replace...xxx Ago. How?
I have some cached pages and I want to display how long ago certain
articles were written.

But how can I display "This article was written 'yyy days' ago" when
the whole page is cached?

I cannot do a simple search and replace as I would need to know when
the articles were written to compare them with the current time, (I
have more than one article with different dates saved in the pages).

I was thinking of tags, something like '<%article date=xxxxx>'.
And preg_replace( "/<%article date=(xxx)>/", ('yyyy'), $data );

But how can I use the 'xxx' to calculate the 'yyy'?

How else would you do it?

Search And Replace
I want to find a way, whereby I can detect any occurence of a text string in a variable (lets say $desc), that occurs immediately after a </UL> and insert a start and end <P></P> around that text string (immediately after the </UL>.  Can anyone advise how I could achieve this using something like preg_replace? Code:

Search And Replace A Character
I have these lines of codes for simple search and replace:

Search & Replace Function?
I have some textfield that users will enter data into on my web site
and then I'll use php and write it to mysql - for security purposes,
is there a function or way to make sure that they only enter in alpha
and numeric data?

Advanced Search Replace
im developing a script which grabs remote html files and shows them on the local server, ive written some code which changes the path of image files to point to the files on the remote server, this code can be seen below: Code:

Search And Replace In Preg_replace
Im trying to figure out how to search replace the var in a preg_replaceThis is the basic code:

$search = array(
'#[item](.+?)[/item]#mis',
);

$replace = array( '<a href="page.php?item=$1">$1</a>',);

$link = preg_replace ( $search, $replace, $link );

However if the 'item' has apostrophe in the '$1' I want that replaced as well. Anyone have ideas on how to do that?

Cache Post Method With Php (search Results)
when you're searching and you click away from the resulting hits page and want to come back, you might get this messae:
data has expired from post method .. blah-blah ..

could be annoying, because if the pages use sessions the soulution that U'd think of doesn't seem to work, but instead U got2 use this line:

session_cache_limiter('private, must-revalidate');

(cuortesy (borrowed it from) of php.net, users contributed section at headers) that person sais the "must revalidate" part is crucial .

Regular Expressions -- Search And Replace Again
I have $content variable which is having following format

$content="hello world! <br> @hero@ is great.
he is very good than @actor@."


now i want to replace @hero@ with
<a href='a.php?word=hero'>hero</a>

and to replace @actor@ with
<a href='a.php?word=actor'>actor</a>


pls help me out.
how can i use

preg_replace() ; ereg_replace();

Search And Replace In Text File
I have a text file with 30 or so lines. Each line has this format:

sometext somevalue. They are separated by a single space.

I want to search in the file for "sometext" and replace "somevalue" with a particular string.

Ignore Whitespace During Search And Replace
I have a file which may have string that need replacing, similar to Smarty templates, for example.

{* EMAIL *}

gets replaced with somebody@somewhere.tld

I want to ignore (or eliminate) any whitespace between the {* *} delimiters, but nowhere else. Basically I'm looking for the equivalent of a regular expression that would not take accout of whitespace, sort of like

$pattern = "/EMAIL/i"

would not take account of case. The /x modifier will not do what I want since it ignores whitespace in the pattern, not in the text being searched.

The only thing I can think of for the moment is to explode, process, and implode the string, but I figure there has to be a better way.

Preg_match/replace To Fix A Search Query
I am working on a script to handle a search query. In some instances,
the query could come through as "isbn:%20#############" (where %20 is
an encoded space and the colon is optional). Basically I want to
strip off the ISBN portion and leave just the numbers if that is the
case.

Orignally I was trying
$value = $_GET["query"];
if (preg_match("isbn:?%20", $value))
{
$isbn = preg_replace("isbn:?%20", "", $value)
}
else
{
$isbn = $value
}

Search/replace Leaving Holes
I am using the following code that works great EXCEPT that I don't want the tags it finds to be replaced with spaces but rather I would like for them to be actually deleted so that when I view the code I don't have say the <tbody> tag and then a blank line and then the <tr> tag,

I would prefer to have the <tbody> tag removed and have NO space between the <table> and the <tr> tags. I really hope this makes sense. I have tried &@127; which I though was the html entity code for the delete key but it doesn't seem to work. PHP Code:

Eregi Search And Replace For Some Text
I'm trying to do a search and replace for some text. For example, I have a word that is 'history', I want to replace every occurence of 'history' with:

<a href="history.html">history</a>

Now, that's easy, I can do that - however, as 'history' could also be 'History', I want to ensure that the format of 'history' stays the same. For example: $strRep = 'history'

$str = eregi_replace($strRep, '<a href="history.html">'.$strRep.'</a>, $my_other_string);

That's fine - however if history is capitalised (History), then I have a problem:

$str = eregi_replace($strRep, '<a href="history.html">'.$strRep.'</a>, $my_other_string);

because the above example would lowercase History to history.

Dictionary Search Definition Replace Of Text
I'm trying to search a weather report for matches to the keys in my associative dictionary array and replace them with the $term => $definition.

following is my code. again, any advise appreciated.

REF: full php source PHP Code:

Search File For Line And Replace With Update
I am trying to search through a file for a line. My line that I will be searching is in a cron flat file. I need to search that file for a line simirlar to:

59 23 * * * wget -q http://www.site.com/runPage.php?usr=name

When the line is found, I need to make changes to it. I have read the file into a variable with fread, is that the best way to get this information for the type of search and replace I am trying to do?

From what I have read in past posts, it seems like strstr is a quick way to go or would strpos be? Or, do I have to do more than that?

I Need To Search And Replace Lines Of Html Code
I need to search and replace lines of html code using regular expressions. In the example below, all of the information between "href="/ and LAST_MODIFIED="0"> varies from individual entry to entry and has to be ignored.

Can someone write the general expression I need to use? I've been trying to get it right to no avail.

Search For...

Search And Replace Database Sites Column
Im trying to search and replace database sites column options with $snr which is set by the user.

[Speed] Multiple Scans Through Variable For Search/replace
At the moment I am developing a app that uses templates.
In the templates I have placeholders like this:

Dear ***FIRSTNAME***<br>
You have subscribed to ***LISTSUBSRIBE***.
etc

The ***XXXX*** must be replaced with values created in my script.

I am a bit worried about the speed and wonder which approach will be
fastest. A straightforward solution would be to run a str_replace($arrSearch,$arrReplace), where $arrSearch contains the strings to be
replaced by the corresponding values in $arrReplace.

Is this a fast solution?
Will a regexpression approach be faster?

Does anybody have experience with this or advise?
Or should I just try a few and benchmark it?

String Replace?
I was using this function to replace some code inside my scripts:

$title = ereg_replace( "_", " ", $string[0]);

but now I only need to add another character at the end of this $title string. How would I go about doing that?

String Replace
all i need to replace a space in a string of code... basically when
it creates this link it calls up the state name Like "New Mexico", how
would i replace the space in New Mexico making it newmexico. my code
is below.

<a href="<?php echo(urlencode($_GET['state2']));?>/<?php
echo(urlencode($_GET['city2']));?>main.php?state2=<?php
echo(urlencode($_GET['state2']));?>&city2=<?php
echo(urlencode($_GET['city2']));?>"></a>

Help With String Replace...
I've got the problem with string replace,
i've got a string like:
/adsf/sdfd34/sdf/435ff/sdfdf
and i need to delete the last characters before "/", so it would
become:
/adsf/sdfd34/sdf/435ff/
I am trying to make a file manager of a sort, and need to make a link
"UP", which would take the user up one level in a directory...
I tried to use str_replace, seems its not the one,
thn i tried to use preg_replace, seems it is the one i need, but i'm
nowhere
near there...
Thats my last effort:
$output = preg_replace("/(/*$)/","/", $input);

Replace Value In A String
I want to replace 'xxx' with &#3912;' (for example) in a string $chaine. How can I do ?

String Replace
I am in the process of writing a script to process a file that is outputted by another program we are writing. We are exporting the file to a plain text file in the following format

"ID", "Title", "Filename", "AID", "arID", "size", "bit", "Freq", "Dur", "Path", "Owner", "Gr", "date"

My problem is, I need to read in each line, whoch I am currently doing with fgets and convert the above into mysql insert statements. What I was thinking that I need to to is to the above string is:-

1. Convert all " to ' using ereg_replace()
2. Addslashes to string to escape any special characters
3. Wrap with insert statement
4. Write to Database

However thinking about that process, once I addslashes, all ' will then be ' So the final insert statement would look like :-

'ID', 'Title', 'Filename', 'AID', 'arID', 'size', 'bit', 'Freq', 'Dur', 'Path', 'Owner', 'Gr', 'date'

and any other character inside some of those fields whoch are also escaped. Is this going to cause any major problems when inserting into DB?? Should I add an extra step in there some where to convert all " to someting allowed, addslashes then change the previous step back to ' for the insert statement?

String Replace
I have a string like below.

$string = "Inner peace, which is peace of mind, is not the sole possession of yogis and hermits. You too can enjoy it without becoming a yogi or a hermit.

Click here to read the article."

I have to replace "Click here blablab" with "";

But we cannt guess the words followed by "Click here"

so i need to replace a sub string which starts with "Click here or click here" and ends with ". or !"

String Replace Help With A URL
I have a form field that will allow a user to post their website for outside linking

I want to make sure that the http:// is always present so when i link to it links outside my site.  However I want to make sure there aren't links to ftp:// or https:// and that the http:// is always present any ideas? I'm bad at regex but i'm sure someone knows a way?

String Replace
I have  a string containg a S  sign.  How can  I remove it?

String Replace
say i have an array

$var = array('name' => 'mark', 'city' => 'some city'); ...etc

and i have a block of text

"Hi <[name]>, do you live in <[city]>?"

how should i efficiently replace the <[]> vars with their matching key vals in my array?

Removing A String From A File -- Best Method
I have a situation where I want to remove a string from a file and
write it to disk before I do further work with it. It's a malformed
xlm document with a string that causes our parsing to choke. I know
exactly where the string occurs, and exactly what it is.

So what is the best method to remove the string from the file? I'm
used to working with an array of each file line from the file()
function, but that seems like it might be overkill in this situation.

How Do I Replace Text In A String...
I have a form setup to take text from a user and insert it into a MySQL database. The problem lies when the user uses an apostrophe in his text.

The apostrophe causes the mysql_query statement to end early because it thinks the apostrophe is part of the syntax, not knowing it's only part of the value.

Example:

If the user submits the text "I'm from the Shire!" when it's submitted to MySQL it thinks the statement ends at I' and thus causes a failed query.

How can I escape or process these text strings to avoid this?

Replace Bad Words From A String
Want to replace bad words from a string.I have a list of bad words and allowed words in an array. 

For example,$allowedwords = array ("*inner", "*outer");
$badwords = array ("inner", "outer");

I want to remove the bad words and similar to bad words and allowed those allowed words similar to bad word.example string: This is an inner text in *inner with spinner.Output like : This is an **** text in *inner with sp****.

Replace String Using Wildcards
I am trying to remove some tags from an XML document that I do not need.

<string id="4466.8" encoding="repr">email</string>

I want to remove the whole tag for the string but keep the content in the middle, the problem is that the id changes, so is there a way to use a 'wildcard' character in the replace code to replace any character found?

   $data=str_replace('<stringid="4466.8" encoding="repr">', '  ', $data);

I saw a post that /S should work for any non whitespace character, this does not seem to work though... any idea's?

Replace Part Of String
just found a problem with part of my project if a ' is present then it screws up the sql query-

so, i need toget rid of it, would the best way be to,

use regex, and see if string a contains a ' || string b etc

and if so, use str_replace("'","",$string);

Wildcard For String Replace
In the following code I need to replace SOMENAME with a wildcard. SOMENAME changes on a regular basis so I have no constant. Code:

Replace Every Character In A String If It Is Not Alphanumeric
Has anyone an idea how i can replace every character in a string if it is not alphanumeric ?

something like eregi_replace, but i don't know how i say in regex NOT.

Replace Part Of String In Between Two Other Parts?
I'm trying to do is an str_replace or something within only a set of other strings. What I'm doing with some text that I put into a database is added a <br> whenever the ASCI character 10 (carraige return) comes up. It's like this.
$text = eregi_replace(10, "<BR>", $text);

what keeps happening though, is that when I make an HTML table in the text, it adds a <br> to that too, and since it's inside the table, it just adds the newline to outside of the table or something and screws everything up.

So, what I want to do is only have it replace the newline with a <br> if it isn't inside of a <table></table> string. I've been all over the PHP documentation and have yet to see something that might work.

Remove/replace Coontents From A String
I have a string variable that holds the content of an HTML page. I want to remove/replace all the data inside the html comment tag.[ie. everything between <!-- and -->]This is because I want to do some validation. So I should remove the unwanted data.Do u know how to do it in PHP?

Replace More Than One Word At A Time In A String?
I want to replace/highlight more than one word in a string. How do I do it? The following code works great but it only highlights/replaces one word in the string. Code:

Execute Ancestor Method Before Descendant Method From Another Method
Is there any way to invoke the ancestor method and then the descendant
method? I'm not saying:

parent::method();
...
<script for the current method>

What I'm looking for is to manually execute the ancestor method
(bypassing the descendant method) and then execute the descendant
method from 'another' method. All of this execution is done from
another method. Reflection class or something?

Parse A Txt File And Replace Each (newline) By A String
i want to aparse a txt file and to replace each new line by a string like (+) for example:
this text:

ahahah
jhtd
bgt

become:
ahahah+jhtd+bgt

Find And Replace Query Variable In URI String
I am trying to find and replace the query variable relating to the session id "sid=". This is the portion of the script that has to find out where the sid= is in the string and replace it with an updated version that contains the session id. It is not finding "?s=" nor "&s=" when I run it any of the following urls.

http://www.mysite.com/?func=home&sid=
http://www.mysite.com/index.php?func=home&sid=
http://www.mysite.com/?sid=&func=home
http://www.mysite.com/index.php?sid=&func=home

I commented out the parts which do not have a bearing on the basic string search function.
PHP Code:

Search A String And Return String Between Char?
I have a string like this;

Full Name (Department)

How can I split that string into seperate strings for Full Name and Department, so that everything before the () is the full name and everything between the () is the department?

Is There A Function To Search A String Within Another String ?
for e.g, fnding the word "hello" in this string : "hello world"...

Search String Delimited In Another String
I have a string (Website referrer).

Example: http://www.google.com/search?q=MY STRING HERE&hl=tl&client=firefox-a&channel=s&rls=org.mozilla:en-US:official&hs=dXZ&start=30&sa=N

I need to extract the keywords searched (example in the above case: "MY STRING HERE").

I think I need the string between "q=" and the next appearing "&".

How can I do this?


Copyright © 2005-08 www.BigResource.com, All rights reserved