php search and replace - php

I am trying to create a database field merge into a document (rtf) using php
i.e if I have a document that starts
Dear Sir,
Customer Name: [customer_name], Date of order: [order_date]
After retrieving the appropriate database record I can use a simple search and replace to insert the database field into the right place.
So far so good.
I would however like to have a little more control over the data before it is replaced. For example I may wish to Title Case it, or convert a delimited string into a list with carriage returns.
I would therefore like to be able to add extra formatting commands to the field to be replaced. e.g.
Dear Sir,
Customer Name: [customer_name, TC], Date of order: [order_date, Y/M/D]
There may be more than one formatting command per field.
Is there a way that I can now search for these strings? The format of the strings is not set in stone, so if I have to change the format then I can.
Any suggestions appreciated.

You could use a templating system like Smarty, that might make your life easier, as you can do {$customer_name|ucwords} or actually put PHP code in your email template.

Try a RegEx and preg_replace_callback:
function replace_param($matches)
{
$parts = explode(',',$matches[0]);
//$parts now contains an array like: customer_name,TC,SE,YMD
// do some substitutions and:
return $text;
}
preg_replace_callback('/\[([^\]]+)\]/','replace_param',$rtf);

You can use explode on it to separate them into array values.
For Example:
$customer_name = 'customer_name, TC';
$get_fields = explode(',', $customer_name);
foreach($get_fields as $value)
{
$new_val = trim($value);
// Now do whatever you want to these in here.
}
Sorry if I'm not understanding you.

Related

How do I create merge tags in a PHP/MySQL app?

I'm writing a PHP/MYSQL SaaS app and I'm currently working on email functionality (using Swift). I plan to save email templates to the MySQL database (each tenant will be able to customize them). However, I also need to include dynamic data in the templates ("merge tags" like first name and last name). I tried simply storing {$test} in the DB but that didn't work. Is there something I need to do after pulling the data from MySQL to merge variables into the text before passing it to Swift?
I'm not familiar with the Swift library, but a quick glance at the documentation didn't turn up anything about parsing messages to insert variables. That means you'll likely need to do that yourself.
One way you might do it, is to come up with your own (arbitrary) syntax for holding a variable's position in a message. For example, you might want to use {%VAR_NAME%} or something.
So you can save your templates like:
Hello {%recipient_name%},
This is to inform you that invoice #{%invoice_num%} is available as of {%invoice_date%}.
Thank you, {%sender_name%}
And then, assuming that template is stored in $email_body, you could do a string replace (either str_replace(), or something like preg_replace(). For something this simple, I wouldn't suggest bogging things down with a regular expression search).
Below is an example of how you might go about doing it. You can build the $search and $replace arrays however you would like, but I just laid it out like this to be more human readable.
// Original body:
$email_body = "Hello {%recipient_name%},
This is to inform you that invoice #{%invoice_num%} is available as of {%invoice_date%}.
Thank you, {%sender_name%}";
// Easily readable input values
$values = array(
'recipient_name' => $db_value['recipient_name'],
'invoice_num' => $db_value['invoice_num'],
'invoice_date' => date("Y-m-d"),
'sender_name' => $_SESSION['user_name']
);
// Break it up into the search and replace arrays
$search = array();
$replace = array();
foreach ($values AS $index => $value)
{
$search[] = "{%" . $index . "%}"; // Wrapping the text in "{%...%}"
$replace[] = $value;
}
// Do the replacement
$email_body = str_replace($search, $replace, $email_body);
The main idea here is that you will be replacing placeholders with a specific syntax (eg {%VALUE%}) with a real value. How you generate the $search and $replace variables is up to you.
This will output something like:
Hello Foo,
This is to inform you that invoice #123456 is available as of
2017-05-19.
Thank you, Bar

Return filenames from a list of files

So I have a list of file names which I wish to pull to then put each one into an array.
Here is an example of the list I will be attempting to pull data from:
-------------
PENDING: (fs) gm_construct.bsp
PENDING: (fs) gm_flatgrass.bsp
...
Would a regular expression be able to parse through this list and just pull these bits:
gm_construct
gm_flatgrass
for example?
each entry would then need to be pushed into an array.
Would this expression also be able to run through a list much longer than this and also handle different prefixes like:
ttt_terrortown
pseudocode:
str.replaceAll("PENDING: (fs) ", "");
str.replaceAll(".bsp", "");
str.replaceAll("-", "");
str[] = str.split("\n");
the str[] will contain a list of your file names.
This basically replace all the "PENDING" stuff and the ".bsp" stuff and split the lines.
Hope this helps!
P.S., this does not require regex at all! (the easier the better)
In the end a friend came up with a little regex to do what I wanted. Might not be as simple as other answers, but it's the one I'm personally going to use, and works fine for my use case.
preg_match_all("/(?<=fs\)).*?(?=\.bsp)/", $maps, $map_list);
This did the trick for me. Splits each file name up into an array which I can then iterate through.

PHP Replace tags / placeholders / markers in text string with dynamic values

Basically, what I want to achieve is dynamically replace {SOME_TAG} with "Text".
My idea was to read all tags like {SOME_TAG}, put them into array.
Then convert array keys into variables like $some_tag, and put them into array.
So, this is how far I got:
//Some code goes here
$some_tag = "Is defined somewhere else.";
$different_tag = 1 + $something;
Some text {SOME_TAG} appears in different file, which contents has been read earlier.
//Some code goes here
preg_match_all('/{\w+}/', $strings, $search);
$search = str_replace(str_split('{}'),"",$search[0]);
$search = array_change_key_case( array_flip($search), CASE_LOWER);
...some code missing here, which I cant figure out.
Replace array should look something like this
$replace = array($some_tag, $different_tag);
//Then comes replacing code and output blah blah blah..
How to make array $replace contain variables dynamically depending on $search array?
Why not something along the lines of:
<?php
$replace = array(
'{TAG_1}' => 'hello',
'{TAG_2}' => 'world',
'{TAG_3}' => '!'
);
$myString = '{TAG_1} {TAG_2}{TAG_3}{TAG_3}';
echo str_replace(array_keys($replace), array_values($replace), $myString);
If I understand correctly:
You're working on trying to create a customizable document, using {TAGS} in order to represent replaceable areas that can be filled in with dynamic information. At some point in time while replacing the {TAGS} with the dynamic information, you want the dynamic information to be stored in automatically generated basic variable names, as $tags.
I'm not sure why you want to convert these tags to basic variables instead using them entirely as array keys. I would like to point out that this represents a security or functionality hole - what happens if someone puts {REPLACE} in as a tag in your document? Your replace array would get overwritten with dynamic data, and your whole program would fall apart. Either that, or the whole replace array would get dumped in for {REPLACE}, making for a very messy document with perhaps data you don't WANT them to have in it. Perhaps you have this dealt with - I don't have all the context here - but I thought I'd point out the risk factor.
As for a better solution, unless there's some specific need that you're addressing by going through $tags instead of using using the $replace array directly, I like #Emissary's answer.

How to use textarea as input to check duplication and invalid?

My idea is to use a textarea to let the user copy email name address etc.... to it.
The copied data must have delimiter between each value.
However, my questions are:
How can i detect the delimiter used in copied data?
How to manipulate? Store each into different array according to the location? but what if there is some error between eg. if one row has one more entry eg. email name address adress2 when other are email name address
Actually i am doing some process from outlook express export txt file or data copied from excel sheet
For those outlook express export file, there are some spacing for each email that without name .So the problem is occur eg.
aa#aa.com name1 bb#bb.com cc#cc.com name2
Thanks for your kindly help.
You would use explode for this (http://php.net/manual/en/function.explode.php).
If you can ask the users to enter each piece of data on a new line, you can then split the textarea contents by the \n character:
e.g.
$myarray = explode("\n", $textarea_str);
Then each element of the array can be split by the delimiting comma:
foreach ($myarray as $row)
$eachline[] = explode(",", $row);
Then validate the individual items that you've extracted from the delimited data as if they have come individually.
You have to explode(',', $_POST['emails]), then run trough that array and check/trim/validate-email all elements for proper format.
you can pre inform the user ,email address must be separated by (ur delimitor may be comma and so).On php side just explode(delimitor,$_REQUEST['text_area_name']);
Oh, nice question . You are trying to find what is the delimiter used in the copied text . I cannot say a perfect solution, but you may create an algorithm like this .
Consider possible delimiters ex : , ' " | etc.
Explode the text with each delimiter in consideration . count the number of elements returned in each array
For , which delimiter you got the higher number of elements in array , may be used by the user
You can fine tune the code
This is a simple example .
Thanks

Assistance with building an inverted-index

It's part of an information retrieval thing I'm doing for school. The plan is to create a hashmap of words using the the first two letters of the word as a key and any words with the two letters saved as a string value. So,
hashmap["ba"] = "bad barley base"
Once I'm done tokenizing a line I take that hashmap, serialize it, and append it to the text file named after the key.
The idea is that if I take my data and spread it over hundreds of files I'll lessen the time it takes to fulfill a search by lessening the density of each file. The problem I am running into is when I'm making 100+ files in each run it happens to choke on creating a few files for whatever reason and so those entries are empty. Is there any way to make this more efficient? Is it worth continuing this, or should I abandon it?
I'd like to mention I'm using PHP. The two languages I know relatively intimately are PHP and Java. I chose PHP because the front end will be very simple to do and I will be able to add features like autocompletion/suggested search without a problem. I also see no benefit in using Java. Any help is appreciated, thanks.
I would use a single file to get and put the serialized string. I would also use json as the serialization.
Put the data
$string = "bad barley base";
$data = explode(" ",$string);
$hashmap["ba"] = $data;
$jsonContent = json_encode($hashmap);
file_put_contents("a-z.txt",$jsonContent);
Get the data
$jsonContent = file_get_contents("a-z.txt");
$hashmap = json_decode($jsonContent);
foreach($hashmap as $firstTwoCharacters => $value) {
if ($firstTwoCharacters == 'ba') {
$wordCount = count($value);
}
}
You didn't explain the problem you are trying to solve. I'm guessing you are trying to make a full text search engine, but you don't have document ids in your hashmap so I'm not sure how you are using the hashmap to find matching documents.
Assuming you want a full text search engine, I would look into using a trie for the data structure. You should be able to fit everything in it without it growing too large. Nodes that match a word you want to index would contain the ids of the documents containing that word.

Categories