Skip to content Skip to sidebar Skip to footer

Find Strings In Text

I have a table with column 'company_name'. Now with some third party apps I receive short strings like this: Somebody has sent item to 'stack-exchange'. I want to find row with st

Solution 1:

Edit: Since you can't identify what part of the input string is the company name, you need to check your existing values for company_name in your table against the string. For example, in PHP:

$input = 'Somebody has sent item to "stack-exchange"';
$result = mysql_query('SELECT company_name FROM table');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if strpos($input, $row['company_name']) === False {
        print"Company name is not in this row!"/* Substitute whatever action you want here */
    } else {
        print"Company name is in this row!"/* Substitute whatever action you want here */
    }
}

Dealing with User Input

Make sure that the input is sanitized before including it as part of a SQL query. Otherwise you make your code vulnerable to hacking.

Unfortunately, since some of the strings you receive are inputted by users, you can't be sure that they'll match what you have in your database. For example, "stack-exchange" could reasonably be represented as "Stack Exchange", stack exchange, StackExchange, etc. So you'll need to standardize the input to match the way you store company names in your database. For example, you could make all characters lowercase and replace all spaces or punctuation with hyphens. This doesn't rule out edge cases like incorrect or variant spellings, but that's beyond the scope of this question.

If the third-party strings you receive reliably contain the company name in double quotation marks (and double quotation marks are not used to indicate anything else in those strings), you can retrieve the company name using PHP. Then you can use a SQL WHERE clause to get the relevant rows.

$input  = 'Somebody has sent item to "stack-exchange"';
$parts = explode('"', $input);
$company_name = $parts[1];
$sql_query = 'SELECT * FROM table WHERE company_name="' . $company_name . '"'

Solution 2:

I think you need to explain the question better, since I can interpret this in at least 2 ways: i) The string provided in the email is a partial match with some data in a column called company-name: Use the like expression either way around, adding % as required eg, '%'+companyname+'%' like emailstring [which will find 'stack-exchange company' from 'stack-exchange provided in the email]

ii) There are multiple columns, each named after a company... eg, id, company1, company2, stack-exchange-company, company4

If your db supports dynamic sql (eg, most flavours of SQLServer) you can compute the sql then use set @sqlexpr = 'select stack-exchange from mytable' exec(@sqlexp)

Otherwise, you'll need to dynamically create the sql prior to calling the db.

Post a Comment for "Find Strings In Text"